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
About Question enthuware.ocpjp.v7.2.1301 :
Moderators: Site Manager, fjwalraven
-
- Posts: 47
- Joined: Mon Apr 08, 2013 7:55 pm
- Contact:
-
- Site Admin
- Posts: 10388
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v7.2.1301 :
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
HTH,
Paul
-
- Posts: 53
- Joined: Thu Nov 22, 2012 12:01 am
- Contact:
Re: About Question enthuware.ocpjp.v7.2.1301 :
"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.
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.
-
- Site Admin
- Posts: 10388
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v7.2.1301 :
You are right. This statement is not required now because the code was changed to include <Person>.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.
Fixed.
thank you for your feedback!
Paul.
Who is online
Users browsing this forum: No registered users and 2 guests