user472221
user472221

Reputation: 3114

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.

how can I print this list with System.out.println ? thanks

Upvotes: 2

Views: 2892

Answers (2)

jjnguy
jjnguy

Reputation: 138864

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.

Upvotes: 7

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181270

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.

Upvotes: 5

Related Questions