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.
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.
toString(). You must match the exact method signature in my post. You have an upper-case T in your method.toString(), not ToString(). Java is case-sensitive.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.
toString method?toString method you must use the exact same casing. Right now, you are using ToString (capital initial T). Using the @Override annotation is useful. Use it. It would have given you a compiler error if you tried to override a non-existant parent method.