Corjava
Corjava

Reputation: 340

Trying to print out the contents of an ArrayList

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);

Upvotes: 10

Views: 87301

Answers (5)

vels4j
vels4j

Reputation: 11298

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]...]

Upvotes: 3

Michael Yaworski
Michael Yaworski

Reputation: 13483

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);

Upvotes: 8

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

Override toString() method on Point class.

class Point implements Comparable<Point>{

    @Override
    public String toString() {
         return "x =" + x  + ", y="+y;
    }
}

Upvotes: 2

Geo
Geo

Reputation: 760

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);
}

Upvotes: 6

musical_coder
musical_coder

Reputation: 3896

Change it to:

System.out.println(""+list.get(i).x);  //Or whatever element in `Point` you want to print

The reason you were getting an unexpected result is that your list consists of Point objects. So calling list.get(i) returns an entire Point, whereas you want to specify that field in the Point to print out.

Upvotes: 0

Related Questions