Trying to print out the contents of an ArrayList

2020-07-06 06:52发布

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

标签: java
5条回答
男人必须洒脱
2楼-- · 2020-07-06 06:56

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.

查看更多
一夜七次
3楼-- · 2020-07-06 06:57

Override toString() method on Point class.

class Point implements Comparable<Point>{

    @Override
    public String toString() {
         return "x =" + x  + ", y="+y;
    }
}
查看更多
我想做一个坏孩纸
4楼-- · 2020-07-06 07:08

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);
查看更多
▲ chillily
5楼-- · 2020-07-06 07:10

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]...]
查看更多
Luminary・发光体
6楼-- · 2020-07-06 07:15

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);
}
查看更多
登录 后发表回答