Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to print out the contents of an ArrayList

Tags:

java

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);
like image 941
Corjava Avatar asked Nov 17 '13 04:11

Corjava


4 Answers

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);
like image 155
Michael Yaworski Avatar answered Nov 04 '22 19:11

Michael Yaworski


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);
}
like image 31
Geo Avatar answered Nov 04 '22 19:11

Geo


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]...]
like image 3
vels4j Avatar answered Nov 04 '22 18:11

vels4j


Override toString() method on Point class.

class Point implements Comparable<Point>{

    @Override
    public String toString() {
         return "x =" + x  + ", y="+y;
    }
}
like image 2
Prabhakaran Ramaswamy Avatar answered Nov 04 '22 19:11

Prabhakaran Ramaswamy