[英]getting the fields of objects from an arraylist in java
Hi I have an array list that has seven objects with type "Points" 嗨,我有一个数组列表,有七个类型为“点”的对象
my "Points" class has 2 fields (1) int x ,(2) int y. 我的“Points”类有2个字段(1)int x,(2)int y。
how can I print this list with System.out.println
? 如何使用
System.out.println
打印此列表? thanks 谢谢
What you need to do first is override the toString()
method of your Point class: 首先需要做的是覆盖Point类的
toString()
方法:
Be very careful that you use the exact signature I have provided below. 请务必小心使用我在下面提供的确切签名。 Otherwise, the
toString
will not work as expected. 否则,
toString
将无法按预期工作。
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
Then, you can just loop over all of the Points and print them: 然后,您可以循环遍历所有点并打印它们:
for(Point p: pointList) {
System.out.println(p);
}
Alternatly, you can just call System.out.println(pointList)
to print the entire list to one line. 或者,您可以调用
System.out.println(pointList)
将整个列表打印到一行。 This is usually less preferred than printing each element on its own line, because it is much easier to read the output if there is one element per line. 这通常不如在自己的行上打印每个元素更受欢迎,因为如果每行有一个元素,则更容易读取输出。
You should override Point
's toString
method: 你应该重写
Point
的toString
方法:
public class Point {
int x,y;
@Override
public String toString() {
return "X: " + x + ", Y: " + y;
}
}
Then just iterate & print: 然后迭代并打印:
for (Point p : points) {
System.out.println(p);
}
points
is the ArrayList
instance containing your 7 Point
class instances. points
是包含7 Point
类实例的ArrayList
实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.