0

What is the expected result when the type parameter is not defined such as in the below code- Code Segment 1:

java.util.Set set = new java.util.TreeSet();
set.add(2);

Code Segment 2:

java.util.Set set = new java.util.TreeSet();
set.add("2");

Code segment 1 and 2 run fine. Code Segment 3:

java.util.Set set = new java.util.TreeSet();
set.add("2");
set.add(3);

Code Segment 4:

java.util.Set set = new java.util.TreeSet();
set.add(2);
set.add("3");

Code segment 3 and 4 fail with following errors respectively:

Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String
    

So does java take up the first addition as the default type for the set? Also, the error seems to be weird, shouldn't it be Integer to String for Code Segment 3 and String to Integer for Code Segment 4?

Additionally, what happens for other collections if type parameter is not defined?

Aadarsh
  • 41
  • 6

0 Answers0