打印 Collection class 元素的最佳方式是什么?

What is the best way to print elements of a Collection class?

我正在研究 java 中的集合 API,并通过两种不同的方式打印出集合中的元素。我需要知道在任何情况下哪种方法最好。

第一种方法是在 Collection 接口中(隐式地)使用 .toString() 方法。 第二种方法是使用迭代器并访问每个元素并将其打印出来。 (这段代码有注释)

public class Test  {

    static Set<String> mySet1 = new HashSet<>();
    static Set<String> mySet2 = new LinkedHashSet<>();

    public static void main(String[] args) {

       String[] arr = {"hello","world","I","am","Tom"};
       for(int i=0; i<arr.length;i++){
           mySet1.add(arr[i]);
           mySet2.add(arr[i]);
       }

       System.out.println("HashSet prinitng...");
      /* Iterator iter1 = mySet1.iterator();
       while(iter1.hasNext()){
           System.out.println(iter1.next());
       }*/

       System.out.println(mySet1);

       System.out.println("LinkedHashSet printing");
       /*
       Iterator iter2 = mySet2.iterator();
       while(iter2.hasNext()){
           System.out.println(iter2.next());
       }*/

       System.out.println(mySet2);
    }
}

哪个更好,为什么?

在Java8中,您可以简单地:

mySet2.forEach(System.out::println);

早期版本:

for (String str : mySet2)
    System.out.println(str);