"Simple Java" HashSet vs TreeSet vs Linkedhashset

Source: Internet
Author: User
Tags comparable

The main reason for using set collections is because there are no duplicate elements in the set collection. The set collection has three common implementation classes: Hashset,treeset,linkedhashset. When to choose which one to use is very important. Simply put, if you focus on performance, you should use hashset; If you need an ordered set of sets, you should use TreeSet if you need a set collection to save the original element insertion order, you should use Linkedhashset.

Set interface

The set interface inherits the collection interface. The set collection does not allow duplicate elements inside, and each element must be unique. You simply add elements to the set collection, and the repeating elements are automatically removed.

Hashset,treeset,linkedhashset Contrast

HashSet is based on a hash table, with no order of elements, and the time complexity of the add, remove, and contains methods is O (1).

TreeSet are tree-based (red-black trees), elements are ordered, and the Add, remove, and contains methods have a time complexity of O (log (n)). Because the element is ordered, it provides several related methods such as first (), Last (), HeadSet (), Tailset (), and so on;

Linkedhashset between HashSet and TreeSet, is based on hash tables and linked lists, supports the insertion order of elements, and the time complexity of the basic method is O (1);

TreeSet Example
New Treeset<integer>(Tree.add);tree.add(tree.add);Tree.add ( Iterator<Integer> Iterator = tree.iterator (); System.out.print ("Tree Set Data:");  while (Iterator.hasnext ()) {    + "");}

Result output:

Tree Set Data:12 34 45 63

Now, let's change the element type, in the INSERT, first define a dog class, as follows

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

Then, add several dog objects to TreeSet as follows:

 Public classQ17 { Public Static voidMain (string[] args) {TreeSet<Dog> Dset =NewTreeset<dog>(); Dset.add (NewDog (2)); Dset.add (NewDog (1)); Dset.add (NewDog (3)); Iterator<Dog> iterator =Dset.iterator ();  while(Iterator.hasnext ()) {System.out.print (Iterator.next () )+ " "); }    }}

The above code, compile OK, but run the Times wrong, as follows:

Exception in thread "main" Java.lang.ClassCastException:simplejava. Dog cannot is cast to java.lang.Comparable
At Java.util.TreeMap.compare (treemap.java:1188)
At java.util.TreeMap.put (treemap.java:531)
At Java.util.TreeSet.add (treeset.java:255)
At Simplejava. Q17.main (q17.java:22)

Why is it? Because TreeSet is ordered, the dog class needs to implement the CompareTo () of the Java.lang.Comparable interface, as follows:

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

Result output:

1 2 3HashSet Example
        New Hashset<dog>();        Dset.add (new Dog (2));        Dset.add (new Dog (1));        Dset.add (new Dog (3));        Dset.add (new Dog (5));        Dset.add (new Dog (4));        Iterator<Dog> Iterator = dset.iterator ();          while (Iterator.hasnext ()) {            + "");        }

Result output:

5 3 2) 1 4

Note that the order is indeterminate.

Linkedhashset Example
 linkedhashset<dog> dset = new  Linkedhashset<dog>();        Dset.add ( new  Dog (2 new  Dog (1 new  Dog (3 new  Dog (5 new  Dog (4 <Dog> Iterator = Dset.iterator ();  while   (Iterator.hasnext ()) {SYSTEM.O Ut.print (Iterator.next ()  + "" ); }

The result output is as follows, saving the insertion order:

2 1 3 5 4 performance test

The following code tests the performance of these three class add methods:

Random r =NewRandom (); HashSet<Dog> HashSet =NewHashset<dog>(); TreeSet<Dog> TreeSet =NewTreeset<dog>(); Linkedhashset<Dog> Linkedset =NewLinkedhashset<dog>(); //Start Time        LongStartTime =System.nanotime ();  for(inti = 0; i < 1000; i++) {            intx = R.nextint (1000-10) + 10; Hashset.add (NewDog (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 (NewDog (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 (NewDog (x)); }        //End TimeEndTime =System.nanotime (); Duration= EndTime-StartTime; System.out.println ("Linkedhashset:" + duration);

As a result, we can find that hashset performance is the best (Note: The above code I own local testing, hashset not necessarily faster than linkedhashset ... ).

hashset:2244768
treeset:3549314
linkedhashset:2263320

This test is not very precise, but it can basically reflect that TreeSet is the worst performing because it needs to be sorted.

Related reading: ArrayList vs. LinkedList vs. Vector

Link: http://www.programcreek.com/2013/03/hashset-vs-treeset-vs-linkedhashset/

"Simple Java" HashSet vs TreeSet vs Linkedhashset

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.