Email address:
Password:
SCJP/OCPJP 1.6 certification
Practice Exams and Training
SCJP Online Training » Discussions

what is the result of attempting to compile and run the program

Hi,



import java.util.*;

public class Test{

public static void main(String args[]){

TreeSet<Test> at=new TreeSet<Test>();

at.add(new Test());

at.add(new Test());

at.add(new Test());

System.out.println(at.first());

}


In this question how it deals System.out.println(at.first());

I don't understand why it doesn't throw the Runtime error.From where it understand the method at.first()

It DOES throw a runtime error - ClassCastException. But that's NOT on the line where you try to call at.first(), but on the very first line where you try to add the first Tree object. This is because, as explained in the explanation, TreeSet want to sort the objects as you add, and to do that, the objects need to be cast-able to Comparable. Since Test does not implement Comparable, the internal casting attempt makes it throw a ClassCastException

ExamLab © 2008 - 2024