2

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

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

5 Comments

In my "point" I have overrided the ToString method. and in the other class ,I want to print them ,but I can not .this is my code:
public void getList(List list) { for(int i=0;i<list.size();i++){ System.out.println(list.get(i).toString()); }
it prints :Class.Point@c4bcdc Class.Point@4b4333 Class.Point@128e20a
@user, the problem is with your casing of toString(). You must match the exact method signature in my post. You have an upper-case T in your method.
@user: it's toString(), not ToString(). Java is case-sensitive.
5

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.

4 Comments

In my "point" I have overrided the ToString method. and in the other class ,I want to print them ,but I can not .this is my code:
Can you edit your question to show the code you used to override toString method?
public String ToString(){ return "X" +x+ "Y"+y; }
There you go. Java is case sensitive. If you want to override 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.