Java Collection Framework - HashSet & TreeSet Classes

The Collection Framework provides two general purpose implementations often Set interface, HashSet and TreeSet. More often than not you will use a HashSet for storing your duplicate-free collection. For efficiency objects added to a HashSet need to implement the hashCode() method in a manner that properly distributes the hash codes. While most system classes override the default hashCode() implementation of the Object, when creating your own class to add to a HashSet remember to override hashCode().

The TreeSet implementations useful when you need to extract elements from a collection in a sorted manner. It is generally faster to add elements to the HasSet then convert the collection to a TreeeSet for sorted traversal.

To optimize HashSet space usage , you can tune initial capacity and load factor. TreeSet has no tuning options, as the tree is always balanced, ensuring log(n0 performance for insertions, deletions and queries
.

Example

import java.util.*;

public class HashTreeSetEx{
  public static void main (String args[]){
   

Set set = new HashSet(){

      set.add("one");
set.add("two");
set.add("three");
set.add("four");
set.add("one");
System.out.println(set);
Set sortedSet= new TreeSet(set);
System.out.println(SortedSet);
    }  
  }  
}    

The program produces the following output. The duplicate entry is olypresent once and the second line outputs sorted

[one, two, three, four]
[four, one, three, two]

Note that these implementation is not synchronized. If multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using the Collections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set:

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

SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));

Explore the other Interface and Classes of Java Collection Framework

Collection Interface
Iterator Interface
Set Interface
List Interface
ListIterator Interface
Map Interface
SortedSet Interface
SortedMap Interface
HashSet & TreeSet Classes
ArrayList & LinkedList Classes
HashMap & Treemap Classes
Vector and Stack Classes

 
 

Collection Framework
Collection Interface
Iterator Interface
Set Interface
List Interface
ListIterator Interface
Map Interface
SortedSet Interface
SortedMap Interface
HashSet & TreeSet Classes
ArrayList & LinkedList Classes

HashMap & Treemap Classes
Vector & Stack Classes

Use of this website constitutes acceptance of the AllAppLabs.com Terms and Conditions