Java 试图打印出 ArrayList 的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20027269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying to print out the contents of an ArrayList
提问by Corjava
I'm trying to print out the contents of the ArrayList "list", but I keep getting what I think is the locations of the elements and not the contents.
我试图打印出 ArrayList“列表”的内容,但我不断得到我认为是元素的位置而不是内容的位置。
import java.util.*;
public class Assignment23 {
public static void main (String[] args){
ArrayList<Point> list = new ArrayList<Point>();
for(int i = 0; i < 99; i++){
list.add(new Point());
}
Collections.sort(list);
System.out.println(""+list);
}
}
class Point implements Comparable<Point>{
int x = (int)(Math.random()*-10);
int y = (int)(Math.random()*-10);
采纳答案by Michael Yaworski
To print out the contents of the ArrayList
, use a for loop
:
要打印出 的内容ArrayList
,请使用for loop
:
for (Point p : list)
System.out.println("point x: " + p.x ", point y: " + p.y);
回答by musical_coder
Change it to:
将其更改为:
System.out.println(""+list.get(i).x); //Or whatever element in `Point` you want to print
The reason you were getting an unexpected result is that your list consists of Point
objects. So calling list.get(i)
returns an entire Point
, whereas you want to specify that field in the Point
to print out.
您得到意外结果的原因是您的列表由Point
对象组成。因此调用会list.get(i)
返回一个完整的Point
,而您想在Point
要打印出来的 中指定该字段。
回答by Geo
You will find you get much better results for this and in many situations if you implement toString
for Point
and most classes that you write. Consider this:
如果你toString
为Point
你编写的大多数类实现,你会发现在很多情况下你会得到更好的结果。考虑一下:
@Override public String toString()
{
return String.format("(%d,%d)", x, y);
}
回答by vels4j
Over write toString method in point
在点上重写 toString 方法
class Point implements Comparable<Point>{
int x = (int)(Math.random()*-10);
int y = (int)(Math.random()*-10);
@Override
public String toString()
{
return "["+x+","+y+"]";
}
}
Usage is same :
用法相同:
Collections.sort(list);
System.out.println("Points["+list+"]);
You will get output like
你会得到类似的输出
Points[[20,10],[15,10]...]
回答by Prabhakaran Ramaswamy
Override toString()
method on Point class.
覆盖toString()
Point 类的方法。
class Point implements Comparable<Point>{
@Override
public String toString() {
return "x =" + x + ", y="+y;
}
}