Monday 29 December 2014

Java : Collection Framework : TreeSet (Non Comparable element)


Click here to watch in Youtube :
https://www.youtube.com/watch?v=GFQ_ww0sNNk&list=UUhwKlOVR041tngjerWxVccw

TreeSetExample.java
import java.util.TreeSet;

/*
 * Example of TreeSet() constructor.
 */
public class TreeSetExample
{
    public static void main( String[] args )
    {
        /*
         * Constructs a new, empty tree set, sorted according to the natural
         * ordering of its elements.
         * 
         * All elements inserted into the set must implement the Comparable
         * interface.
         * 
         * Furthermore, all such elements must be mutually comparable:
         * e1.compareTo(e2) must not throw a ClassCastException for any elements
         * e1 and e2 in the set. If the user attempts to add an element to the
         * set that violates this constraint (for example, the user attempts to
         * add a string element to a set whose elements are integers), the add
         * call will throw a ClassCastException.
         */
        TreeSet<StringBuffer> treeSet = new TreeSet<StringBuffer>();
        
        StringBuffer stringBuffer = new StringBuffer("Ram");

        treeSet.add(stringBuffer);
        

        System.out.println("treeSet : " + treeSet + "\n");

    }
}
Output
Exception in thread "main" java.lang.ClassCastException: java.lang.StringBuffer cannot be cast to java.lang.Comparable
    at java.util.TreeMap.compare(Unknown Source)
    at java.util.TreeMap.put(Unknown Source)
    at java.util.TreeSet.add(Unknown Source)
    at TreeSetExample.main(TreeSetExample.java:28)

To Download TreeSetDemoNonComparable Project Click the below link
https://sites.google.com/site/javaee4321/java-collections/TreeSetDemoNonComparable.zip?attredirects=0&d=1

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • No comments:

    Post a Comment