TreeSet 和 HashSet

TreeSet and HashSet

为什么 HashSet 不能同时作为以下问题的答案?当我测试代码时,HashSetTreeSet 都给出了相同的输出,但正确答案似乎是 TreeSet。代码如下:

import java.util.*;

public class Example {
    public static void main(String[] args) {
        // insert code here
        set.add(new Integer(2));
        set.add(new Integer(1));
        System.out.println(set);
    }
}

Which code, inserted at line 4, guarantees that this program will output [1, 2]?

  1. Set set = new TreeSet();
  2. Set set = new HashSet();
  3. Set set = new SortedSet();
  4. List set = new SortedList();
  5. Set set = new LinkedHashSet();

HashSet 无序的 ,这具体意味着 Java 不保证键(以及值)的存储顺序。另一方面,TreeSet 以自然顺序存储其元素。

来自 Javadoc for TreeSet:

The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used. and If the objects can not be sorted in natural order than use compareTo() method to sort the elements of TreeSet object but hashmap is using equals() method to compare the elements.

选项是:

  1. Set set = new TreeSet();

根据doc

The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

所以这是 正确答案 因为插入后自然排序将是 [1,2]

  1. Set set = new HashSet(); HashSet 未排序,因此也不能保证自然排序。这不是正确答案。

  2. Set set = new SortedSet(); SortedSet 是一个接口。

  3. List set = new SortedList(); 由于显而易见的原因,这绝对不是正确的答案。

  4. Set set = new LinkedHashSet(); Set接口的Hashtable和链表实现,具有predictable迭代顺序。在这种情况下,输出将是 [2,1].

  1. Set set = new TreeSet();

是的,因为 TreeSet 是有序集,键 2112.

的自然顺序
  1. Set set = new HashSet();

否,因为 HashSet 不保证任何订单。

  1. Set set = new SortedSet();

编译错误:SortedSet是一个接口,无法实例化。

  1. List set = new SortedList();

编译错误:Java.

中没有标准 SortedList class
  1. Set set = new LinkedHashSet();

顺序保证为21(插入顺序)。