Java_Alert
Java_Alert

Reputation: 1179

HashSet and TreeSet in Java

Set s = new HashSet();

boolean b[] = new boolean[5];
b[0] = s.add("a");
b[1] = s.add(new Integer(5));
b[2]= s.add("a");
b[3] = s.add(new Object());
b[4] = s.add("4");
for(int i=0;i<b.length;i++){
    System.out.println(b[i]);
}

This is giving me this output as expected : -

true
true
false
true
true

But when I am using Treeset

Set s = new TreeSet();

It is giving me this exception.

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at java.lang.Integer.compareTo(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at com.sunil.questions.TreeSetExample.main(TreeSetExample.java:15)

I want to know why it is showing me this behavior.

Upvotes: 1

Views: 2928

Answers (4)

Dinakar Prasad Maurya
Dinakar Prasad Maurya

Reputation: 371

As we know that TreeSet sort element while adding into it. Here u are adding string and integer at same time in TreeSet so u got error. U can use different tree set for string and integer and then can merge.

Upvotes: 1

Aashray
Aashray

Reputation: 2763

Use generics to instantiate your collections. You have a HashSet/TreeSet which contain String as well as Integer. This is not recommended. TreeSet is sorted so it will not be able sort with String and Integer as no implicit conversion happens. Use Comparator interface if you want to sort String and Integer.

Upvotes: 2

Dariusz
Dariusz

Reputation: 22241

The root of evil here is not using generics. You are instantiating a collection of unknown objects and expect Java to work correctly with them. Unfortunately, this time it can't - comparing String with Integer is not possible, at least not by default.

Use Set<String> s = new HashSet<String>(); and Set<String> s = new TreeSet<String>();. The compiler will then tell you that you can't add Integer to a collection, you will be forced to convert the Integer to a String and all will work well.

Upvotes: 3

Prasad Kharkar
Prasad Kharkar

Reputation: 13556

  • TreeSet is sorted, it cannot sort String and Integer together. Thats why you are getting this exception.

If you just add the same type of elements, then you will not get exception.

This is where the generics come into picture, if you want your collections to be type safe, then you can declare them as Set<String> set = new HashSet<String>() or Set<Integer> set = new TreeSet<Integer>();

Using this method, compiler itself will stop you from adding integers to Set<String> and likewise.

Upvotes: 6

Related Questions