30. HashSet, TreeSet, and Enumset of set sets in Java

Source: Internet
Author: User
Tags comparable set set

The set set is a subset of collection, and the set set is basically the same as collection, without providing any additional methods, except that the set does not allow repeating elements.

Set set of 3 implementation classes: HashSet, TreeSet, Enumset

  

First, HashSet

 Public class Hashset<e>extends abstractset<e>implements Set<e>, cloneable, Java.io.Serializable

HashSet is a typical implementation of the set interface, and HashSet stores the elements by the hash algorithm, so it has good access and lookup performance. It has the following characteristics:

1, can not guarantee the order of the elements, the order may be changed.

2, HashSet is asynchronous.

3, the collection element value can be null.

4. When an element is deposited into the HashSet collection, HashSet calls the object's Hashcode () method to get the Hashcode value of the object, and then determines where the object is stored in hashcode based on the HashSet value.

"Note": HashSet the criteria for determining the equality of two elements are: 1, two objects are equal by Equals (), 2, two objects return values equal to the Hashcode () method. Only when the first two conditions are met, HashSet is judged to be the same element.

HashSet also has a subclass Linkedhashset, whose collection determines where elements are stored based on the hashcode value of the element, but it maintains the order of the elements with the linked list, so that the elements appear to be saved in the order in which they are inserted, that is to say, When traversing the Linkedhashset collection element, it accesses the elements in the collection in the order in which they are added. So Linkedhashset's performance is slightly lower than hashset, but it will perform well when iterating through all the elements because it maintains the internal order in the list.

Second, TreeSet

 Public class extends Implements Navigableset<e>, Cloneable, java.io.Serializable

TreeSet is the only implementation of the Sortset interface, and TreeSet ensures that the collection elements are in a sorted state. Compared to HashSet, TreeSet also offers several additional methods:

1, Comparator Comparator (): Returns the Comparator used by the current set, or returns NULL, indicating a natural sort.

2. Object First (): Returns the element in the collection.

3, Object last (): Returns the final element in the collection.

4, Object lower (object E): Returns an element in the collection before the specified element.

5, Object Higher (object E): Returns an element in the collection that is after the specified element.

6, SortedSet subset (from Element,to Element): Returns the subset of this set, ranging from the from element to the to element (closure).

7, SortedSet HeadSet (toelement): Returns a subset of this set, consisting of elements less than toelement.

8, SortedSet Tailset (fromelement): Returns a subset of this set, consisting of elements greater than or equal to fromelement.

1  Public Static voidMain (string[] args) {2TreeSet num=NewTreeSet ();3Num.add (5);4Num.add (2); 5Num.add (10);6Num.add (-9);7SYSTEM.OUT.PRINTLN (num);//output: [ -9,2,5,10] The collection element is already in the sorted state8System.out.println (Num.first ());//Output-99System.out.println (Num.last ());//output);TenSystem.out.println (Num.headset (4));//output -9,2 Returns a subset less than 4 OneSystem.out.println (Num.tailset (5));//output 5,10 Returns a subset greater than or equal to 5 ASystem.out.println (Num.subset ( -9,5));//output -9,2 Returns a subset greater than or equal to 9 less than 5 -}

As you can see from the above procedure, TreeSet is not sorted by element insertion order, but by the value of the element. TreeSet supports two sorts of sorting methods: natural sorting and custom sorting.

1. Natural sort: TreeSet invokes the CompareTo (Object obj) method of the collection element to prioritize the size relationship between elements, and then arranges the collection elements in ascending order. If you attempt to add an object to TreeSet, the object's class must implement the comparable interface, or the program will have a classcastexception exception.

2. Custom sorting: If you need to implement a custom sort, you can use the help of the comparable interface, which contains an int compare (O1,o2) method, which is used to size two numbers, and if a positive integer is returned, the o1>o2; returns 0. Indicates the O1=O2; if a negative integer is returned, the o1<02 is indicated.

Note: You cannot add objects of different types to treeset, otherwise you will cause classcastexception exceptions.

Third, Enumset

1. All values in Enumset must be values of the specified enumeration type, and its elements are ordered in order to determine the order in which the enumeration values are defined in the enumeration class.

2. The Enumset collection does not allow the addition of a null element, otherwise it throws a NullPointerException exception.

3. The Enumset class does not expose any constructors to create an instance of the class, and the program should create the Enumset object through the static method it provides, which is commonly used as the static method:

A, static Enumset AllOf (class ElementType): Creates a Enumset collection that contains all the enumeration values in the specified enumeration class.

b, Static Enumset Complementof (Enumset s): Creates a enumset whose element type is the same as the element type in the specified Enumset, and the new Enumset collection contains the original Enumset collection does not package

The remaining enumeration values for this enumeration class.

C, Static Enumset CopyOf (collection C): Use a normal collection to create a Enumset collection.

D, Static Enumset copyOf (Enumset E): Creates a enumset with the same element type, same collection element as the specified enumset.

E, static Enumset noneof (Class ElementType): Creates an empty enumset that has an element type of the specified enumeration type.

F, static enumset of (E first,e...rest): Creates a enumset that contains one or more enumeration values, and the multiple enumerated values passed in must belong to the same enumeration class.

G, static Enumset range (E from,e to): Creates a Enumset collection that contains all the enumeration values from the From enumeration value to the range of the to enumeration value.

1 enumsesson{2 Spring,summer,fall,winter3 }4 5  Public classTest6 {7      Public Static voidMain (string[] args)throwsparseexception{8         //creates a Enumset collection where the collection element is the enumeration value in all Sesson9Enumset Es1=enumset.allof (Sesson.class);TenSystem.out.println (ES1);//[SPRING, SUMMER, FALL, WINTER] One         //creates an Enumset empty collection whose collection elements are enumerations of the Sesson type AEnumset es2=enumset.noneof (Sesson.class); -System.out.println (ES2);//[] -         //adding elements manually the Es2.add (sesson.summer); - Es2.add (sesson.spring); -System.out.println (ES2);//[SPRING, SUMMER] -         //creates a collection with the specified enumeration value +Enumset es3=Enumset.of (sesson.summer,sesson.winter); -System.out.println (ES3);//[SUMMER, WINTER] +Enumset es4=Enumset.range (sesson.spring, sesson.fall); ASystem.out.println (ES4);//[SPRING, SUMMER, FALL] atEnumset es5=Enumset.complementof (ES4); -System.out.println (ES5);//[WINTER] -     } -}

Summarize:

1, hashset performance is better than TreeSet, because treeset need an additional red-black tree algorithm to maintain the order of the elements of the collection, only when the need to maintain a sort of set, will be used TreeSet.

2, Enumset is the best performance, but it can only save enumeration values.

3. They are thread insecure.

30. HashSet, TreeSet, and Enumset of set sets in Java

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.