shantanu
shantanu

Reputation: 2028

Able to cast the ArrayList<Set<String>> to ArrayList<String> String without class cast exception

I am doing following operations.

    Set<Set<String>> set1 = new HashSet<Set<String>>();
    Set<Set<String>> set2 = new HashSet<Set<String>>();

    set1.add(new HashSet<String>(Arrays.asList("s1","s2")));
    set1.add(new HashSet<String>(Arrays.asList("s4","s5")));

    set2.add(new HashSet<String>(Arrays.asList("s5","s4")));


    ArrayList<String> ob = (ArrayList<String>)CollectionUtils.subtract(set1, set2);
    ArrayList<Set<String>> ob1 = (ArrayList<Set<String>>)CollectionUtils.subtract(set1, set2);
    System.out.println(ob);
    System.out.println(ob1);

It is giving following output.
[[s2, s1]]
[[s2, s1]]

Shouldn't it give the class cast exception in first case?

Thanks,
Shantanu

Upvotes: 0

Views: 118

Answers (2)

Matthew T. Staebler
Matthew T. Staebler

Reputation: 4996

The type arguments that you supply for ob1 and ob2 are not present at runtime. The println method does not carry about the actual types since it is just calling the Object#toString method. You would not get a ClassCastException unless you tried to use the objects stored in the array lists directly as the incorrect type.

For example, you would get an exception if you did the following.

String s = ob.iterator.next();

Upvotes: 0

Amit Deshpande
Amit Deshpande

Reputation: 19185

Generics is compile time feature of java language so in your code at run time what you are doing is casting it to ArrayList so eventually it is an ArrayList so no execption.

Also your code does not do anything with returned 'ArrayList' it just prints it which calls toString() method so your code has currently no possiblity to have ClassCastExpection

Upvotes: 2

Related Questions