I'm trying to print out the contents of the ArrayList "list", but I keep getting what I think is the locations of the elements and not the contents.
import java.util.*;
public class Assignment23 {
public static void main (String[] args){
ArrayList<Point> list = new ArrayList<Point>();
for(int i = 0; i < 99; i++){
list.add(new Point());
}
Collections.sort(list);
System.out.println(""+list);
}
}
class Point implements Comparable<Point>{
int x = (int)(Math.random()*-10);
int y = (int)(Math.random()*-10);
Change it to:
The reason you were getting an unexpected result is that your list consists of
Point
objects. So callinglist.get(i)
returns an entirePoint
, whereas you want to specify that field in thePoint
to print out.Override
toString()
method on Point class.To print out the contents of the
ArrayList
, use afor loop
:Over write toString method in point
Usage is same :
You will get output like
You will find you get much better results for this and in many situations if you implement
toString
forPoint
and most classes that you write. Consider this: