Thatís the thing about people who think they hate computers. What they really hate is lousy programmers. Larry Niven

TreeSet

Language Java | Level Intermediate | Category Java collections framework (JCF) | 2015-07-24 11:53:24

0 Comments


Definition

TreeSet is implemented using a red-black tree structure. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

Character

TreeSet does not allow to store duplicates.
It is not thread-safe and throw ConcurrentModificationException when multiple threads access TreeSet object
It is much slower than other types of sets.
A TreeSet uses the least space and tends to be slowest compare than other set implementation.

source Code

								
package com.careerdrill.collections.set;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class TreeSetUse {

	public static void main(String[] args) {
		
		int []array={34,67,45,34,27,98,56};
		System.out.print("Array of elements before insert the data to tree set: "+ Arrays.toString(array));
		Set< Integer > tree = new TreeSet< Integer >();
		
		for(Integer i : array)
			tree.add(i);
		
	 
		Iterator< Integer > iterator = tree.iterator();
		System.out.print("\nTree set elements which sorted ascending order: ");
 

		while (iterator.hasNext()) {
			System.out.print(iterator.next() + " ");
		}


	}

}
						

Output

    					 
Array of elements before insert the data to tree set: [34, 67, 45, 34, 27, 98, 56]
Tree set elements which sorted ascending order: 27 34 45 56 67 98
    					 
					    

Comparison

HashSet LinkedHashSet TreeSet
HashSet does not maintain insertion order LinkedHashSet maintains insertion order TreeSet provides natural sorting
HashSet allows null LinkedHashSet allows null TreeSet does not allow null
O(n) O(1) O(logn)
Implemented using hash table Implemented using doubly linked list Implemented using red block tree
Not allowed to store duplicates Not allowed to store duplicates Not allowed to store duplicates
Compare HashSet uses equals() and hashCode() methods Compare HashSet uses equals() and hashCode() methods Comparable or comparator interface implementation

When to use

When you want sort elements using Comparator implementation or natural sorting, you can use TreeSet.

0 Comments



Please login to add comments.