简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM