TreeSet in Java and null acceptance in TreeSet?


TreeSet in Java and null acceptance in TreeSet?

TreeSet in Java and null acceptance in TreeSet?
  • The underlying data structure is the balanced tree.
  • Duplicate objects are not allowed.
  • Insertion order not preserved.
  • Heterogeneous objects are not allowed otherwise we will get runtime exception saying ClassCastException.
  • Null insertion possible (only once).
  • TreeSet Implement Serializable and Cloneable but not RandomAccess Interface.
  • All objects will be inserted based on some sorting order it may be default natural sorting order or customized sorting order.
  • If we are depending on Default Natural sorting order compulsory the object should be homogeneous and Comparable otherwise we will get runtime exception saying ClassCastException.
  • An object is said to be comparable if and only if and only if the corresponding class implements the Comparable interface.
  • String class and all wrapper classes already implement the Comparable interface. But StringBuffer doesn’t implement comparable interface hence we got ClassCastException in above example.
package com.java4us;

import java.util.TreeSet;

public class Test {
    public static void main(String[] args) {
        TreeSet t = new TreeSet();
        t.add(new StringBuffer("Welcome"));
        t.add(new StringBuffer("to"));
        t.add(new StringBuffer(""));
        System.out.println(t); //RE:-java.lang.StringBuffer incompatible with java.lang.Comparable

Leave a Reply

Your email address will not be published. Required fields are marked *