❮ Previous Next ❯

JAVA TreeSet Tutorial

public classTreeSet<E>
extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, Serializable
where E - the type of elements maintained by this set


Constructors:


1. TreeSet():Creates an empty TreeSet object where elements are inserted
according to default natural sorting order.

2. TreeSet(Comparator c) : Creates an empty TreeSet object where elements
are inserted according to customized sorting order.

3. TreeSet t=new TreeSet(SortedSet s):From a SortedSet object, we can create
an equivalent TreeSet object.

4. TreeSet t=new TreeSet(SortedSet s) : From any Collection object, we can
create an equivalent TreeSet object.


Let's see a program on TreeSet

TreeSetExample.java:

package java8s;
import java.util.*;
    public class TreeSetExample
     {
       public static void main(String[] args)
        {
          TreeSet t=new TreeSet();
          t.add(50);
          t.add(35);
          t.add(100);
          //t.add(null); NullPointerException
           //t.add("java"); ClassCastException
          System.out.println(t);
        }
     }
Output

[35, 50, 100]

Null Acceptance:

Let's see another program

Tree Set Demo1.java:

package java8s;
import java.util.*;
    public class TreeSetExample1
     {
       public static void main(String[] args)
        {
          TreeSet t=new TreeSet();
          t.add(new StringBuffer("Sashi"));
          t.add(new StringBuffer("Sneha"
          t.add(new StringBuffer("Sradha"));
          t.add(new StringBuffer("Sanghamitra"));
          System.out.println(t);
        }
     }
Output

Exception in thread "main" java.lang.ClassCastException:
java.base/java.lang.StringBuffer cannot be cast to
java.base/java.lang.Comparable

Note :

  • If we are depending on the default natural sorting order then objects should be homogeneous and Comparable. Otherwise we will get run time exception known as Class Cast Exception.
  • An object is said to be Comparable if and only if the corresponding class implements java.lang.Comparable interface.
  • String class and all wrapper classes implements Comparable interface, but StringBuffer does not implement Comparable interface.
  • Hence in the above program we got ClassCastException.
  • Regards:
    Trilochan Tarai
    SILAN Technology, BBSR
    Mail to : trilochan@silantechnology.com


    ❮ Previous Next ❯



      Tutorials

    Popular Links

    Contact Us

    address Plot No-741,2ND Floor
    Opp. Bhagabati Temple,Jayadev Vihar
          Bhubaneswar-751013
          Email: info@silantechnology.com
          Phone: 0674-2361252
    address
    39877, sundale dr, apt#101, Fremont, California 94538, USA
           Phone: +1(262)388-7619

    facebook twitter google linked in

    © 2018 Silan Technology. All Rights Reserved