SCPJ2 aspirant
Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
Hi Chetan,
i guess you are little bit wrong in your explanation. set and treeset doesnt allow duplicates. but how they implement is different from what you said. if you add string objects, then while adding it uses the string representation to compare whether they are equal or not(to determine duplicates).
But if you add wrapper objects(Integer,Long etc),they use the compareTo method to determine whether they are equal and not the string representation.
just consider this code snippet:
Integer io = new Integer("100");
Long lo = new Long("100");
TreeSet ts = new TreeSet();
ts.add(io);
ts.add(lo);
Iterator it = ts.iterator();
while (it.hasNext()) {
System.out.println("Set Value is : " + it.next());
}
code:
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
this code complies fine, but throws a runtime exception classcastException,since it cant compare an Integer and a Long objects.
Correct me if i am wrong.
Thanks.
TreeSet is using compareTo() to determine order. This is the method which throws the ClassCastException. HashSet only cares about uniqueness and tests with equals(), which, instead of complaining about incompatible objects passed to it, simply returns false (when implemented correctly).TreeSet gives runtime error because it is trying to order its element and it can not compare a Long with an Integer.
The Inner that is named is not the true Inner.