Java Collection series--set HashSet and TreeSet Introduction (10)

Source: Internet
Author: User
Tags iterable set set shallow copy

I. Introduction to Set
Set is a collection that does not contain duplicate elements . More specifically, the set does not contain elements that satisfy e1.equals (E2). For E1 and E2, and contains a maximum of one null element.

Class diagram for set:

1. Inherit from the collection interface, with the method of adding and deleting and checking and changing!

2.AbstractCollection abstract class, implement the collection interface, and implement some of the methods inside, such as IsEmpty, contains and so on.

Two implementation classes for 3.Set, HashSet and TreeSet

    • The essence of hashset realization is that the elements inside the hashmap,hashset are disordered.
    • The essence of TreeSet realization is that the elements inside the treeset,treeset are orderly.

Two. HashSet
1. Overview
HashSet implements a set interface, it is also an unordered collection that does not contain duplicate elements, allows NULL, and only one element is null!

HashSet is also a non-synchronous method, if you want to use in multiple threads, be aware of the synchronous encapsulation!

Set s = Collections.synchronizedSet(new HashSet(...));

HashSet the iterator returned by iterator () is fail-fast.

2. Inheritance relationships and APIs

HashSet API

Classhashset<E>Java. lang. Object inheritorsJava. util. abstractcollection<e> inheritors java . Utile> inheritors java.utile> type parameter: e -this set the types of elements maintained by all implemented interfaces: serializable, cloneable,  Iterable<E>, collection<e>, set<E>   

Linkedhashset inherits the HashSet and implements the set set of the linked list.

(1): Construction method

HashSet()           set,其底层 HashMap 实例的默认初始容量是 16,加载因子是 0.75。HashSet(Collection<? extends E> c) 构造一个包含指定 collection 中的元素的新 set。HashSet(int initialCapacity) 构造一个新的空 set,其底层 HashMap 实例具有指定的初始容量和默认的加载因子(0.75)。HashSet(int initialCapacity, float loadFactor) 构造一个新的空 set,其底层 HashMap 实例具有指定的初始容量和指定的加载因子。

(2) Method:

Boolean Add (E e) If thisThe specified element is added when the set does not already contain the specified element.voidclear () removes all elements from this set. object clone () returns a shallow copy of this HashSet instance: The elements themselves are not copied. boolean contains (object o) if this  Set contains the specified element, the true is returned. boolean isEmpty () If this set does not contain any elements, return true. Iterator<e> Iterator () returns an iterator that iterates over the elements in this set. boolean Remove (object o) if the specified element exists in this set, remove it. int size () returns the number of elements in this set (set).  

3. Summary

The hashset contains a "member variable of type HashMap" Map,hashset operation function, which is actually implemented by map.

There are two ways to traverse:
(1) Using Iterator

First step: Get the HashSet iterator based on iterator ().
Step two: Iterate through the iterators to get the individual elements.

for(Iterator iterator = set.iterator();       iterator.hasNext(); ) {     iterator.next();}

(2) using foreach

The first step is to get an array of HashSet's element collections based on ToArray ().
Step two: Iterate through the array to get the individual elements.

Object[] object = (String[])set.toArray();for (Object obj : object) System.out.printf(obj);

Three. TreeSet
1. Overview
Navigableset implementation based on TREEMAP. The elements are sorted using the natural order of the elements, or sorted according to the comparator provided when the set was created, depending on the construction method used.

2. Inheritance relationships and APIs

TreeSet API
(1) Succession relationship:

 <E >java.lang.object successor Java.util.abstractcollection<E> inheritors Java.util.abstractset<e> successor Java.util.treeset<e> type parameter: E-This set maintains the type of the element all implemented interfaces: Serializable, cloneable, Iterable<E>, Collection< E> Navigableset<E> Set<E>, Sortedset< E>              

Inheriting from Abstractset,abstractset implements the Equals and Hashcode methods.

Implements the Navigableset interface, which means that it supports a range of navigation methods. For example, find the most matching item to the specified target.

Implements the Cloneable interface, which means it can be cloned.

Implements the Java.io.Serializable interface, which means that it supports serialization.

(2) Construction method:

TreeSet()           set,该 set 根据其元素的自然顺序进行排序。TreeSet(Collection<? extends E> c)           构造一个包含指定 collection 元素的新 TreeSet,它按照其元素的自然顺序进行排序。TreeSet(Comparator<? super E> comparator) 构造一个新的空 TreeSet,它根据指定比较器进行排序。TreeSet(SortedSet<E> s) 构造一个与指定有序 set 具有相同映射关系和相同排序的新 TreeSet。

(3) Method:

The Boolean Add (e E) Adds the specified element to thisSet (if the element does not already exist in theSet).Boolean AddAll (collection<? extendsE>c) Add all elements in the specified collection to thisSet.ECeilingEE) return thisThe smallest element in set greater than or equal to the given element, or if no such element exists, returnsNull.voidClear () removes thisAll the elements in the set.ObjectClone () returns a shallow copy of the TreeSet instance. comparator<? SuperE> Comparator () returns to thisThe comparer for sorting the elements in the set;Set uses the natural order of its elements, it returnsNull.Boolean contains (Object o) If thisSet contains the specified element, the returnTrue iterator<E> Descendingiterator () return to thisAn iterator that iterates in descending order on the set element. navigableset<E> Descendingset () returns thisThe inverted view of the elements contained in the set.EFirst () returns thisThe current first (lowest) element in set.EFloorEE) return thisThe largest element in set less than or equal to the given element, or if no such element exists, returnsNull. sortedset<E> HeadSet (E toelement) returns thisA partial view of the set whose elements are strictly less than toelement. navigableset<E> HeadSet (E Toelement,Boolean inclusive) returns thisA partial view of the set whose elements are less than (or equal to, if inclusive istrue) toelement.E Higher (EE) return thisThe minimum element in a set that is strictly greater than the given element, or if no such element exists, returnsNull.Boolean isEmpty () if thisSet does not contain any elements, it returnsTrue iterator<E> iterator () return to thisAn iterator that iterates over the elements of a set in ascending order.ELast () returns thisThe current last (highest) element in set.ELowerEE) return thisSet is strictly less than the largest element of a given element, or if no such element exists, returnsNull.E Pollfirst () gets and removes the first (lowest) element;Set is empty, it returnsNull.E Polllast () gets and removes the last (highest) element;Set is empty, it returnsNull.Boolean Remove (Object o) To assign the specified element from theThe set is removed if the element exists in thisSet).IntSize () returnsThe number of elements in set (The capacity of the set). navigableset<E> subset (E Fromelement,boolean frominclusive, E toelement, boolean toinclusive) returns A partial view of this set, whose elements range from fromelement to toelement. sortedset<e> subset (e fromelement, e toelement) returns a partial view of this set, whose elements range from fromelement (including) to Toelement (not included). sortedset<e> tailset (E fromelement) returns A partial view of this set whose elements are greater than or equal to fromelement. navigableset<e> tailset (E fromelement, Boolean inclusive) returns a partial view of this set whose elements are greater than (or equal to, if Inclusive is true) fromelement. 

3. Summary

(1) Null elements are not allowed in TreeSet! If you add null when adding, a NullPointerException exception is thrown.

(2) TreeSet is based on the TREEMAP implementation. The elements in TreeSet support 2 sorting methods: Natural sorting or sorting according to the Comparator provided when the TreeSet is created. This depends on the construction method used.

(3) TreeSet is a non-synchronous method. The iterator returned by its iterator method is fail-fast.

(4) TreeSet does not support fast random traversal and can only be traversed by iterators!
Example:

A. Using iterator sequential traversal

for(Iterator iter = set.iterator(); iter.hasNext(); ) {     iter.next();} 

B. Using the Foreach

Object[] object = (Object[])set.toArray();for (Object obj : object) System.out.printf(obj);

Four. Source code
TreeSet and HashSet source code is no longer analyzed, the two are based on TreeMap and HASHMAP implementation, but only the corresponding node only key, and no value, so the TreeMap and hashmap more understanding, The understanding of TreeSet and hashset can be very easy.

Five. Summary comparison (usage scenario)

The 1.HashSet is an unordered collection, based on the HashMap implementation; TreeSet is an ordered set, based on the TREEMAP implementation.

A null element is allowed in the 2.HashSet collection, and a null element is not allowed in the TreeSet collection.

3.HashSet and TreeSet are non-synchronous! Pay attention to Fail-fast when using iterator for iterations.

Java Collection series--set HashSet and TreeSet Introduction (10)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.