gpt4 book ai didi

java - 树集和哈希集

转载 作者:行者123 更新时间:2023-12-01 18:11:09 25 4
gpt4 key购买 nike

为什么不能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对于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.

关于java - 树集和哈希集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32879482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com