Arrays Are Not Casted Correctly

Answered

I start off with this code:

private String[] getArray() {
List<String> testList = new ArrayList<String>();
testList.add("Prepare for a ClassCastException");

}

there is a missing return statement so I Alt-Enter and end up with this:

private String[] getArray() {
List<String> testList = new ArrayList<String>();
testList.add("Prepare for a ClassCastException");

return new String[0];
}

I am more likely to want to return the list as an array than a new empty array so I change it manually to this:

private String[] getArray() {
List<String> testList = new ArrayList<String>();
testList.add("Prepare for a ClassCastException");

return testList.toArray();
}

now this doesn't compile so I Alt-Enter and "Cast to 'java.lang.String[]'"

private String[] getArray() {
List<String> testList = new ArrayList<String>();
testList.add("Prepare for a ClassCastException");

return (String[])testList.toArray();
}

This causes a ClassCastException at runtime because the code should be:

private String[] getArray() {
List<String> testList = new ArrayList<String>();
testList.add("Prepare for a ClassCastException");

return testList.toArray(new String[testList.size()]);
}

IDEA shouldn't be creating code that generates runtime errors.

Ideally the Add return intention would return the list as an array straight away though.

There is a "Suspicious cast" inspection but this has to be run manually and doesn't seem to be available as a warning in the right-hand-side gutter.

The Inspection isn't that helpful either because although it finds the issue, there is no fix available (unless you count //noinspection SuspiciousArrayCast as a fix!)

0

Please sign in to leave a comment.