Java Containers & Generics: Three, Hashset,treeset and Linkedhashset comparisons

Source: Internet
Author: User
Tags comparable set set

On a summary of the next ArrayList, LinkedList and vector comparison, today Mason summary of the hash, LinkedList and vector comparison. In fact, we are all collection, but a bit of their own characteristics. That is the different manifestations of data structures.

First, set review

A collection that does not include duplicate elements, including mutable objects , is an unordered collection. Set does not contain elements that are full a.equals (b) to A and B, and have a maximum of one null.
Mason's Memory Palace:
1, not allowed to contain the same elements

2, judging whether the object is the same, according to the equals method

Second, HashSet

A hash algorithm is used to store the elements in the collection, whose element values can be null. It does not guarantee the order in which elements are arranged. Similarly, HashSet is not synchronized, and if multiple threads are required to access it, you can use the Collections.synchronizedset method to wrap it:

Set s = collections.synchronizedset (new HashSet (...));

As in the previous section, when using iterators, you should also pay attention to concurrency modification exception concurrentmodificationexception.

The point to note is that the HashSet set determines that two elements are equal not only to the equals method, but also to the hashcode() method to return the values equally. Look at the following example:

ImportJava.util.HashSet;classeuqalsobj{ Public Booleanequals (Object obj) {return true; }} classhashcodeobj{ Public inthashcode () {return1; }} classhashsetobj{ Public inthashcode () {return2; }      Public Booleanequals (Object obj) {return true; }}  Public classhashsettest{ Public Static voidMain (string[] args) {HashSet Objs=NewHashSet (); Objs.add (Neweuqalsobj ()); Objs.add (Neweuqalsobj ()); Objs.add (Newhashcodeobj ()); Objs.add (Newhashcodeobj ()); Objs.add (Newhashsetobj ()); Objs.add (Newhashsetobj ()); System.out.println ("HashSet Elements:"); System.out.print ("\ t" + Objs + "\ n"); }}

Run a bit and the console output is as follows:

HashSet Elements:    [Email protected]1, [email protected], [email protected], [email protected], [email protected]

The Masons arrived according to the results. First, the order of the permutations is variable.

The Hashsetobj class satisfies our just request, so there is only one in the collection and its hashcode value is 2.

The Hashcodeobj class, although they have hashcode values of 1, are not equal. (In fact, when the hashcode value is the same, this storage location uses a chained structure to hold two Hashcodeobj objects.) )

Similarly, the Equalsobj class they are equal, but their hashcode value is unequal, 1471CB25, 3acff49f respectively.

So, to add mutable objects with HashSet, be aware that when objects are likely to be modified and contradict other objects, we cannot find the exact object we need from HashSet.

Third, Linkedhashlist

HashSet subclasses also have hashcode values to determine the position of the element. However, it maintains the order of elements using a list of links. Memorize two words: ordered .

Orderly refinement, reproduction. For example, a Mason implements a hashset unordered addition and then copies a hashset in the same order . The code is as follows:

 Packagecom.sedion.bysocket.collection;ImportJava.util.HashSet;ImportJava.util.LinkedHashSet;ImportJava.util.Set; Public classlinkedhashlisttest{ Public Static voidMain (string[] args) {/*copy HashSet*/Set H1=NewHashset<string>(); H1.add ("List"); H1.add ("Queue"); H1.add ("Set"); H1.add ("Map"); System.out.println ("HashSet Elements:"); System.out.print ("\ t" + h1 + "\ n"); Set H2=copy (H1); System.out.println ("HashSet Elements after Copy:"); System.out.print ("\ T" + H2 + "\ n"); } @SuppressWarnings ({"Rawtypes", "unchecked" })     Public StaticSet copy (set set) {Set Setcopy=NewLinkedhashset (set); returnsetcopy; }     }

Run a bit and the console output:

HashSet Elements:    [Map, queue, set, List]hashset Elements after Copy:    [Map, queue, set, List]

It can be seen that every data structure has a reason for its existence.

Iv. TreeSet

TreeSet is implemented using a tree structure (a red-black tree), and the elements in the collection are sorted, but the added, deleted, and included algorithm complexity is O (log (n)).

For example, first we define a bird class. (A bird is a Mason's favorite animal)

class bird{    int  size;           Public Bird (int  s)    {        = s;    }           Public String toString ()    {        return size + "";    }}

Then add the bird class with TreeSet.

 Public classtreesettest{ Public Static voidMain (string[] args) {TreeSet<Bird> BSet =NewTreeset<bird>(); Bset.add (NewBird (1)); Bset.add (NewBird (3)); Bset.add (NewBird (2)); Iterator<Bird> iter =Bset.iterator ();  while(Iter.hasnext ()) {Bird Bird=(Bird) iter.next ();        System.out.println (bird); }    }}

Run, the console output is as follows:

Exception in thread "main" Java.lang.ClassCastException:Bird cannot is cast to java.lang.Comparable at    Java.util . Treemap.compare (Unknown source) at    java.util.TreeMap.put (Unknown source) at    Java.util.TreeSet.add (Unknown Source) at    com.sedion.bysocket.collection.TreeSetTest.main (Treesettest.java:29)

The answer is obvious, TreeSet is sorted. So bird needs to implement comparable this interface.

Java.lang.Comparable This interface forces the overall ordering of objects for each class that implements it. This sort is called the natural ordering of the class, and the compareTo method of the class is called its natural comparison method .

Modify the bird as follows:

class Implements Comparable<bird>{    int  size;           Public Bird (int  s)    {        = s;    }           Public String toString ()    {        return size + "bird";    }     @Override    publicint  compareTo (Bird o)    {        return Size- o.size;    }     }

Run again:

Bird No. 1th, number 2nd, bird number 3rd.

Five, performance test comparison

For the above three set sets, we perform a performance test on their Add method:

ImportJava.util.HashSet;ImportJava.util.LinkedHashSet;ImportJava.util.Random;ImportJava.util.TreeSet;classBirdImplementsComparable<bird>{    intsize;  PublicBird (ints) {size=s; }          PublicString toString () {returnSize + "number Bird"; } @Override Public intcompareTo (Bird o) {returnSize-o.size; }     } Public classset{ Public Static voidMain (string[] args) {Random R=NewRandom (); HashSet<Bird> HashSet =NewHashset<bird>(); TreeSet<Bird> TreeSet =NewTreeset<bird>(); Linkedhashset<Bird> Linkedset =NewLinkedhashset<bird>(); //Start Time        LongStartTime =System.nanotime ();  for(inti = 0; i < 1000; i++) {            intx = R.nextint (1000-10) + 10; Hashset.add (NewBird (x)); }        //End Time        LongEndTime =System.nanotime (); LongDuration = EndTime-StartTime; System.out.println ("HashSet:" +duration); //Start TimeStartTime =System.nanotime ();  for(inti = 0; i < 1000; i++) {            intx = R.nextint (1000-10) + 10; Treeset.add (NewBird (x)); }        //End TimeEndTime =System.nanotime (); Duration= EndTime-StartTime; System.out.println ("TreeSet:" +duration); //Start TimeStartTime =System.nanotime ();  for(inti = 0; i < 1000; i++) {            intx = R.nextint (1000-10) + 10; Linkedset.add (NewBird (x)); }        //End TimeEndTime =System.nanotime (); Duration= EndTime-StartTime; System.out.println ("Linkedhashset:" +duration); }}

Run, you can see from the console:

hashset:261099831953782673782

Visible, TreeSet performance is poor because it needs to be compared.

Vi. Summary

Hashset:equlas hashcode

Linkedhashset: Chain-structured

TreeSet: comparison, comparable interface, poor performance

Reprinted from: http://www.bysocket.com/?p=195

Java Containers & Generics: Three, Hashset,treeset and Linkedhashset comparisons

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.