Java基礎之Collections框架Set接口及其使用和源碼分析
Set接口
集合是不能包含重複元素的集合。Set接口只包含從集合繼承的方法,並添加了禁止重複元素的限制。Set還爲equals和hashCode操作的行爲添加了一個更強的契約,而不是從集合接口繼承的契約。允許對Set實例進行有意義的比較,即使它們的實現類型不同。如果兩個Set實例包含相同的元素,則它們是相等的。
Java平臺包含三個通用的Set實現:HashSet、TreeSet和LinkedHashSet。將元素存儲在哈希表中的HashSet是性能最好的實現;但是,它不能保證迭代的順序。TreeSet將元素存儲在紅黑樹中,並根據元素的值對其進行排序;它比HashSet慢得多。LinkedHashSet實現爲一個散列表,其中貫穿着一個鏈表,它根據元素插入到集合中的順序(插入順序)對元素進行排序。
Set使用
Set簡單使用
Collection<String> ops = new HashSet<>();
||
Set<String> sets = new HashSet<>();
//可以使用set去重collection中的重複元素
Collection<String> linkedHashSetR= new LinkedHashSet<String>(c);
Set JDK8操作
#在java 8中使用stream進行去重
c.stream().collect(Collectors.toSet()); //去重
#將數組中的相關的值保存到treeSet中
List<Person> persons = new ArrayList<>();
Person person = new Person();
person.setName("tony");
person.setLast("Smith");
persons.add(person);
Set<String> nameSets = persons.stream().map(Person::getName).collect(TreeSet::new);
Set源碼相關方法
//返回元素的個數
int size();
/**
判斷是否爲空
*/
boolean isEmpty();
/**
判斷集合中是否包含指定的元素
*/
boolean contains(Object o);
/**
返回集合的迭代器
*/
Iterator<E> iterator();
/**
將集合轉換爲數組
*/
Object[] toArray();
/**
返回指定類型的數組
*/
<T> T[] toArray(T[] a);
// Modification Operations
/**
添加元素,這個和collect的不同實現有把不同的規則
*/
boolean add(E e);
/**
移除指定的元素
*/
boolean remove(Object o);
/**
set中是否包含指定集合中的所有元素
*/
boolean containsAll(Collection<?> c);
/**
添加指定集合中的所有元素,會去重
*/
boolean addAll(Collection<? extends E> c);
/**
保留指定集合中的元素
*/
boolean retainAll(Collection<?> c);
/**
移除指定集合中的所有元素
*/
boolean removeAll(Collection<?> c);
/**
清空set集合中的所有元素
*/
void clear();
/**
進行比較操作
*/
boolean equals(Object o);
/**
生產set的hashCode值
*/
int hashCode();
/**
返回一個Spliterator操作
*/
@Override
default Spliterator<E> spliterator() {
return Spliterators.spliterator(this, Spliterator.DISTINCT);
}
基本上和collection的接口中的方法一致,只是在進行add的時候做了
去重的處理。我們看看它的相關實現,看看相關方法的具體實現操作。