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.

Answers


  • 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.


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.


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.


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.


Need Your Help

Search Results Sort order using Sitecore 7 ContentSearch API?

lucene sitecore sitecore7

I am using the Sitecore.ContentSearch API to perform a search which works fine and brings back the expected results.

Adding 2 widgets into gtk with python

python menu tree widget gtk

these are first few tries with python and I want to add 2 widgets to a gtk.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.