Java.util.TreeSet Example


Introduction

Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements NavigableSet interface. The objects of TreeSet class are stored in ascending order.

Java TreeSet contains unique elements only like HashSet.

Access and retrieval times of Java TreeSet are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly.

Difference Between Set And List in Java

Declaration of java.util.TreeSet

public class TreeSet 
extends AbstractSet
implements NavigableSet, Cloneable, java.io.Serializable
{
...
}

Example of java.util.TreeSet

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

public class main {

public static void main (String [] args)
{
//declare a default TreeSet object that will be sorted in an ascending order
//according to the natural order of its elements
TreeSet set = new TreeSet();

//add elements to this set
set.add("Peter");
set.add("Amy");
set.add("John");
set.add("Ivy");
set.add("Hello Kitty");
set.add("Bill");

System.out.println("number of elements in this set : " + set.size());
System.out.println("the first (lowest) element in this set : " + set.first());
System.out.println("the last (highest) element in this set : " + set.last());

System.out.println(set);
//output : [Amy, Bill, Hello Kitty, Ivy, John, Peter]

//Returns an iterator over the elements in this set
Iterator iterator=set.iterator();

while (iterator.hasNext())
{
System.out.println(iterator.next());
}
}
}

Output from The Program

number of elements in this set : 6
the first (lowest) element in this set : Amy
the last (highest) element in this set : Peter
[Amy, Bill, Hello Kitty, Ivy, John, Peter]
Amy
Bill
Hello Kitty
Ivy
John
Peter


Java TreeSet class

張貼留言

0 留言