#java collection -set
- Map for storing a key-value mapping, wherein the key value is not repeated. And also you need the right override equals and hashCode methods
- If we not only need to store duplicate key, do not need to store a value corresponding to the value, you can use set
- set for storing a set of elements will not be repeated, providing mainly the following methods:
- The elements added to the Set
:boolean add(E e) - The elements from the Set
Delete: boolean remove (Object e) - Determining whether the element comprising: boolean contains (Object e)
- The elements added to the Set
1. Set实际上相当于只存储key、不存储value的Map。我们经常用Set用于去除重复元素
2. 原因是:set中的key和map中的key一样,都需要严格的实现equals和hashCode方法,否则无法正确方法set元素
3. Set接口并不保证有序,而SortedSet接口则保证元素是有序的:
* HashSet是无序的,因为它实现了Set接口,并没有实现SortedSet接口;
* TreeSet是有序的,因为它实现了SortedSet接口。
hashSet output:
public class Main {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("pear");
set.add("orange");
for (String s : set) {
System.out.println(s);
}
}
}
While traversing TreeSet, output is ordered, this order is the sort order of elements:
public class Main {
public static void main(String[] args) {
Set<String> set = new TreeSet<>();
set.add("apple");
set.add("banana");
set.add("pear");
set.add("orange");
for (String s : set) {
System.out.println(s);
}
}
}
Queue
队列Queue实现了一个先进先出(FIFO)的数据结构:
通过add()/offer()方法将元素添加到队尾;
通过remove()/poll()从队首获取元素并删除;
通过element()/peek()从队首获取元素但不删除。
要避免把null添加到队列。