This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
When you store the instances of the particular class, in your case, Test class., should implements the Comparable interface. The TreeSet uses this method to sort the instances which you've stored in it. Since, the Comparable is a interface, the compiler can't check it in the compile time!
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
i have done this exam today only,whenever we are talking about the treeset(navigalbe set) ,the elements in it we are adding must be mutually comparable and the type parameter we specify with that must implement comparable interface,else ClassCastException(unchecked)will be thrown.
as test class doesn't implement comparable interface,so program suffers from exceptions at runtime.
mohitkumar gupta wrote:unable to understand the last line of Explanation as given in Exam lab
when the class TreeSet attempts to cast Test into Comparable,a ClassCastException would be Produced
because you are using generics compiler is making sure that all elements you are adding in the treeset must be mutually comparable.
when it saw that test doesn't implements comparable,so it's attempts to cast fails,and an exception will be thrown.
if you post the code here,will help you able to understand more.
When you add any elements into the TreeSet all the elements should be mutually comparable..
If you are not using generic type..then you can add any type elements into the Treeset but while sorting you will get ClassCastException..
please check below code