| | |
    Java Beginner Home
    Table of Contents
    Introduction to Java
    Getting Started with Java
    Basic Language Elements
    Java Operators
    Java Control Statements
    Java Access Modifiers
    Classes and Objects
    Java Constructors
    Object Serialization
    Java Class Inheritance
    Java Object Type Casting
    Abstract class and Interface
    Java Method Overiding
    Java toString Method
    Java String Class
    Java toString Method
    Java String Comparison
    Java StringBuffer
    Java Exceptions
    Singleton Pattern
    Java Threads Tutorial
    Java Collections Framework
    Java Date Util
    Swing Tutorial
    Feedback
    Java books

Java TreeSet

public class TreeSet<E>
extends AbstractSet<E>
implements SortedSet<E>, Cloneable, Serializable



  • This class implements the Set interface and guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements or by the comparator provided at set creation time, depending on which constructor is used.
  • This implementation not synchronized provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

To prevent unsynchronized access to the Set.: SortedSet s = Collections.synchronizedSortedSet(new TreeSet(..));

Below is a TreeSet Example showing how collections are manipulated using a TreeSet

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

public class TreeSetExample {

	public static void doTreeSetExample() {
	}
	public static void main(String[] args) {
		Set treeSet = new TreeSet();
		// the treeset stores Integer objects into the TreeSet
		for (int i = 0; i < 5; i++) {
			treeSet.add(new Integer(i));
		}
		// Since its a Integer Object Set adding any other elements in the Same
		// set will produce a
		// ClassCastException exception at runtime.
		// treeSet.add("a string");
		System.out.print("The elements of the TreeSet are : ");
		Iterator i = treeSet.iterator();
		while (i.hasNext()) {
			System.out.print(i.next() + "\t");
		}
	}
}

Output

The elements of the TreeSet are : 0 1 2 3 4

Download  TreeSetExample.java

 
Page 4 of 8
1
4



 
    Java is a trademark of Sun Microsystems, Inc.
| | |
© Copyright 2007-08 javabeginner.com