javacodex.com
Java Examples
Java Examples
memu home questions

Basic TreeSet Example

This java example is a basic TreeSet example.

Source: (MyTreeSet.java)

import java.util.TreeSet;
 
public class MyTreeSet {
 
   public static void main(String args[]){
 
      TreeSet<String> ts = new TreeSet<String>();
      ts.add("Bill");
      ts.add("Tom");
      ts.add("Harry");
      ts.add("George");
      System.out.println("Size of the set: "+ ts.size());
      System.out.println("Elements: " + ts);
      System.out.println("Removing Tom");
      ts.remove("Tom");
      System.out.println("Elements: " + ts);
 
      System.out.println("Adding another George");
      ts.add("George");
      System.out.println("Elements: " + ts);
   }
}
 

Output:

# java MyTreeSet 
Size of the set: 4
Elements: [Bill, George, Harry, Tom]
Removing Tom
Elements: [Bill, George, Harry]
Adding another George
Elements: [Bill, George, Harry]

Contact: javacodex@yahoo.com