Java 试图打印出 ArrayList 的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20027269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:26:14  来源:igfitidea点击:

Trying to print out the contents of an ArrayList

java

提问by Corjava

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.

我试图打印出 ArrayList“列表”的内容,但我不断得到我认为是元素的位置而不是内容的位置。

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

采纳答案by Michael Yaworski

To print out the contents of the ArrayList, use a for loop:

要打印出 的内容ArrayList,请使用for loop

for (Point p : list)
    System.out.println("point x: " + p.x ", point y: " + p.y);

回答by musical_coder

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 Pointobjects. So calling list.get(i)returns an entire Point, whereas you want to specify that field in the Pointto print out.

您得到意外结果的原因是您的列表由Point对象组成。因此调用会list.get(i)返回一个完整的Point,而您想在Point要打印出来的 中指定该字段。

回答by Geo

You will find you get much better results for this and in many situations if you implement toStringfor Pointand most classes that you write. Consider this:

如果你toStringPoint你编写的大多数类实现,你会发现在很多情况下你会得到更好的结果。考虑一下:

@Override public String toString()
{
     return String.format("(%d,%d)", x, y);
}

回答by vels4j

Over write toString method in point

在点上重写 toString 方法

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

回答by Prabhakaran Ramaswamy

Override toString()method on Point class.

覆盖toString()Point 类的方法。

class Point implements Comparable<Point>{

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