Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

java - 如何在Java中打印出列表的所有元素?(How to print out all the elements of a List in Java?)

I am trying to print out all the elements of a List , however it is printing the pointer of the Object rather than the value.

(我正在尝试打印List所有元素,但是它正在打印Object的指针而不是值。)

This is my printing code...

(这是我的打印代码...)

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

Could anyone please help me why it isn't printing the value of the elements.

(任何人都可以帮助我,为什么它没有印刷出要素的价值。)

  ask by user1335361 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following is compact and avoids the loop in your example code (and gives you nice commas):

(以下是紧凑的,并且避免了示例代码中的循环(并为您提供了漂亮的逗号):)

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

However, as others have pointed out, if you don't have sensible toString() methods implemented for the objects inside the list, you will get the object pointers (hash codes, in fact) you're observing.

(但是,正如其他人指出的那样,如果您没有为列表内的对象实现明智的toString()方法,则将获得要观察的对象指针(实际上是哈希码)。)

This is true whether they're in a list or not.

(无论他们是否在列表中,都是如此。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...