我试图打印出一个列表的所有元素,但它是打印对象的指针,而不是值。

这是我的打印代码…

for(int i=0;i<list.size();i++){
    System.out.println(list.get(i));
} 

有人能告诉我为什么它不打印元素的值吗?


当前回答

下面的代码很紧凑,避免了示例代码中的循环(并提供了漂亮的逗号):

System.out.println(Arrays.toString(list.toArray()));

然而,正如其他人指出的那样,如果您没有为列表中的对象实现合理的toString()方法,您将得到您所观察到的对象指针(实际上是哈希码)。无论它们是否在列表中,都是如此。

其他回答

Java 8 Streams方法…

list.stream().forEach(System.out::println);
   List<String> textList=  messageList.stream()
                            .map(Message::getText)
                            .collect(Collectors.toList());

        textList.stream().forEach(System.out::println);
        public class Message  {

        String name;
        String text;

        public Message(String name, String text) {
            this.name = name;
            this.text = text;
        }

        public String getName() {
            return name;
        }

      public String getText() {
        return text;
     }
   }

尝试重写toString()方法,因为您希望元素将被打印。 打印的方法可以是这样的:

for(int i=0;i<list.size();i++){
    System.out.println(list.get(i).toString());
} 
public static void main(String[] args) {
        answer(10,60);

    }
    public static void answer(int m,int k){
        AtomicInteger n = new AtomicInteger(m);
        Stream<Integer> stream = Stream.generate(() -> n.incrementAndGet()).limit(k);
        System.out.println(Arrays.toString(stream.toArray()));
    }
System.out.println(list);//toString() is easy and good enough for debugging.

AbstractCollection的toString()将非常干净和容易做到这一点。AbstractList是AbstractCollection的子类,因此不需要for循环,也不需要toArray()。

返回此集合的字符串表示形式。字符串表示形式由集合元素的列表组成 它们由迭代器返回的顺序,用方括号括起来 (“[]”)。相邻元素用字符“,”(逗号)分隔 和空间)。通过将元素转换为字符串 String.valueOf(对象)。

如果您正在使用列表中的任何自定义对象,例如Student,则需要重写它的toString()方法(重写这个方法总是好的)以获得有意义的输出

请看下面的例子:

public class TestPrintElements {

    public static void main(String[] args) {

        //Element is String, Integer,or other primitive type
        List<String> sList = new ArrayList<String>();
        sList.add("string1");
        sList.add("string2");
        System.out.println(sList);

        //Element is custom type
        Student st1=new Student(15,"Tom");
        Student st2=new Student(16,"Kate");
        List<Student> stList=new ArrayList<Student>();
        stList.add(st1);
        stList.add(st2);
        System.out.println(stList);
   }
}


public  class Student{
    private int age;
    private String name;

    public Student(int age, String name){
        this.age=age;
        this.name=name;
    }

    @Override
    public String toString(){
        return "student "+name+", age:" +age;
    }
}

输出:

[string1, string2]
[student Tom age:15, student Kate age:16]