[Java] Really scary ClassCastException

less than 1 minute read

Interface of the method to be tested


public class Foo {
    public void process(List<String> arg0) {
        /* See below */
    }
}

a suitable test code you wrote yourself


List<String> arg0 = Arrays.asList("A", "I", "U");

Foo foo = new Foo();
foo.process(arg0);

This is why I get a ClassCastException. I was surprised to see the source of the test.

Why did you bother to cast it?


public void process(List<String> arg0) {
    // ↓ No compile warning!
    List<String> ls = (ArrayList) arg0;

    // below
}

It was horrible code that didn’t even give a compile warning…

Of course, it didn’t fall down. (I’m not saying it’s good because it won’t fall)

test code written by newcomer


List<String> arg0 = new ArrayList<>();
arg0.add("a");
arg0.add("yes");
arg0.add("uu");

Foo foo = new Foo();
foo.process(arg0);