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

这是我的打印代码…

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

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


当前回答

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

其他回答

这取决于List中存储的对象类型,以及它是否有toString()方法的实现。System.out.println(list)应该打印所有标准java对象类型(String, Long, Integer等)。在这种情况下,如果我们使用自定义对象类型,那么我们需要重写自定义对象的toString()方法。

例子:

class Employee {
 private String name;
 private long id;

 @Override
 public String toString() {
   return "name: " + this.name() + 
           ", id: " + this.id();
 }  
}

测试:

class TestPrintList {
   public static void main(String[] args) {
     Employee employee1 =new Employee("test1", 123);
     Employee employee2 =new Employee("test2", 453);
     List<Employee> employees = new ArrayList(2);
     employee.add(employee1);
     employee.add(employee2);
     System.out.println(employees);
   }
}

java 11问题的解决方案是:

String separator = ", ";
String toPrint = list.stream().map(o -> String.valueOf(o)).collect(Collectors.joining(separator));

System.out.println(toPrint);

或者你可以简单地使用Apache Commons实用程序:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ArrayUtils.html#toString-java.lang.Object-

List<MyObject> myObjects = ...
System.out.println(ArrayUtils.toString(myObjects));

列表中的对象必须实现toString,以便将有意义的内容打印到屏幕上。

下面是一个快速测试,可以看出区别:

public class Test {

    public class T1 {
        public Integer x;
    }

    public class T2 {
        public Integer x;

        @Override
        public String toString() {
            return x.toString();
        }
    }

    public void run() {
        T1 t1 = new T1();
        t1.x = 5;
        System.out.println(t1);

        T2 t2 = new T2();
        t2.x = 5;
        System.out.println(t2);

    }

    public static void main(String[] args) {        
        new Test().run();
    }
}

当它执行时,打印到屏幕的结果是:

t1 = Test$T1@19821f
t2 = 5

因为T1没有重写toString方法,所以它的实例T1输出的结果不是很有用。另一方面,T2重写了toString,所以我们控制了它在I/O中使用时打印的内容,我们在屏幕上看到了一些更好的东西。

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