Saturday, August 14, 2010

Arrays: ToDo.java

Courtesy of education.oracle.com











When we compile this code, we get a warning

Note: ToDo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

To fix this, use generics; note how <String> is added to List declaration











Code compiles without warning; however we get runtime error:

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(AbstractList.java:148)
    at java.util.AbstractList.add(AbstractList.java:108)
    at ToDo.main(ToDo.java:6)

The asList() method creates a fixed-size list that is backed by the array, so no additions are possible.

No comments:

Post a Comment