官方文档说明:https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html
Set 的特点
A Set is a Collection that cannot contain duplicate elements.
Allowing Set instances to be compared meaningfully even if their implementation types differ.
Two Set instances are equal if they contain the same elements.
包含三种通用的Set集合实现
HashSet、TreeSet、LinkedHashSet的比较!
- HashSet:which stores its elements in a hash table, is the best-performing implementation; however it makes no guarantees concerning the order of iteration.however it makes no guarantees concerning the order of iteration.
- TreeSet, which stores its elements in a red-black tree, orders its elements based on their values; it is substantially slower than HashSet.
- LinkedHashSet, which is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the set (insertion-order). LinkedHashSet spares its clients from the unspecified, generally chaotic ordering provided by HashSet at a cost that is only slightly higher.
总结:
- HashSet是性能效率最好的,但是无序!
- TreeSet根据值进行排序,比HashSet要慢很多!
- LinkedHashSet 根据元素的插入顺序进行排序!
案例1:假设有一个Collection c 然后你想要用另外一个Collection来存储c的相同元素但是需要去重。Collection<Type> noDups = new HashSet<Type>(c);
如果版本>=8 ,则还可以使用 c.stream() .collect(Collectors.toSet());
注意 :HashSet虽然速度快,但是无序。
案例2:在案例1的基础上要求保持元素在原来的Collection c上的顺序。Collection<Type> noDups = new LinkedHashSet<Type>(c);
案例3: 如果两个Set实例包含相同的元素,那么这两个Set相等。
Collection<String> test1 = Arrays.asList("Java","php","python");
Collection<String> test2 = Arrays.asList("Java","php","python");
System.out.println("same?"+test1.equals(test2));
打印结果为:same?true