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);
To print out the contents of the ArrayList
, use a for loop
:
for (Point p : list)
System.out.println("point x: " + p.x ", point y: " + p.y);
You will find you get much better results for this and in many situations if you implement toString
for Point
and most classes that you write. Consider this:
@Override public String toString()
{
return String.format("(%d,%d)", x, y);
}
Over write toString method in point
class Point implements Comparable<Point>{
int x = (int)(Math.random()*-10);
int y = (int)(Math.random()*-10);
@Override
public String toString()
{
return "["+x+","+y+"]";
}
}
Usage is same :
Collections.sort(list);
System.out.println("Points["+list+"]);
You will get output like
Points[[20,10],[15,10]...]
Override toString()
method on Point class.
class Point implements Comparable<Point>{
@Override
public String toString() {
return "x =" + x + ", y="+y;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With