getting the fields of objects from an arraylist in java
Hi I have an array list that has seven objects with type "Points"
my "Point开发者_运维百科s" class has 2 fields (1) int x ,(2) int y.
how can I print this list with System.out.println
?
thanks
What you need to do first is override the toString()
method of your Point class:
Be very careful that you use the exact signature I have provided below. Otherwise, the toString
will not work as expected.
@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. 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:
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.
精彩评论