Page 1 of 1

About Question enthuware.ocpjp.v7.2.1301 :

Posted: Thu Apr 25, 2013 5:23 pm
by renatumb
In this question, Person class does not implement Comparable interface. Ideally, when you add the first element, since there is nothing to compare this element to, there should be no exception. But when you add the second element, TreeSet tries to compare it with the existing element, thereby throwing ClassCastException because they don't implement Comparable interface.


It really compiles fine but the ClassCastException is thrown when you try add the first element because the class doesnot implement Comparable interface

Re: About Question enthuware.ocpjp.v7.2.1301 :

Posted: Sat Apr 27, 2013 7:18 am
by admin
Yes, and the next line in the explanation that you've quoted says, " However, this behavior was changed in the TreeSet implementation recently and it throws a ClassCastException when you add the first element itself."

HTH,
Paul

Re: About Question enthuware.ocpjp.v7.2.1301 :

Posted: Tue Aug 13, 2013 12:11 am
by icepeanuts
"Also note that since the TreeSet hasn't been typed here ( as in TreeSet<Person> ), the compiler will allow any kind of object to be put into it."

What does it actually mean? I think the TreeSet is type safe because it is declared as TreeSet<Person> set = new TreeSet<Person>(). The compiler doesn't allow any objects other than Person to be added.

Re: About Question enthuware.ocpjp.v7.2.1301 :

Posted: Tue Aug 13, 2013 9:53 am
by admin
icepeanuts wrote:"Also note that since the TreeSet hasn't been typed here ( as in TreeSet<Person> ), the compiler will allow any kind of object to be put into it."

What does it actually mean? I think the TreeSet is type safe because it is declared as TreeSet<Person> set = new TreeSet<Person>(). The compiler doesn't allow any objects other than Person to be added.
You are right. This statement is not required now because the code was changed to include <Person>.
Fixed.

thank you for your feedback!
Paul.