public static void main(String[] args) { // This list is intended to hold only strings. // The compiler doesn't know that so we have to remember ourselves. List Wordlist = new ArrayList(); // Oops! We added a String[] instead of a String. // The compiler doesn't know that this is an error. wordlist.add(args); // Since List can hold arbitrary objects, the get() method returns // Object. Since the list is intended to hold strings, we cast the // return value to String but get a ClassCastException because of // the error above. String word = (String)wordlist.get(0);}
public static void main(String[] args) { // This list can only hold String objects List<String> wordlist = new ArrayList<String>(); // args is a String[], not String, so the compiler won't let us do this wordlist.add(args); // Compilation error! // We can do this, though. // Notice the use of the new for/in looping statement for(String arg : args) wordlist.add(arg); // No cast is required. List<String>.get() returns a String. String word = wordlist.get(0);}