import java.util.*; /** * StringIntegerDemo * CS 2334, Section 001 * Sept 23, 2002 *

* This program demonstrates some of the problems with Collections. *

* @author unknown modified by dfh 19 Sep 2008 * @version 1.0 */ public class StringIntegerDemo { /** * Default constructor. */ public StringIntegerDemo() { } /** * This is the main method for this test program. Since this is a * simple test program, all of our code will be in the main method. * Typically this would be a bad design, but we are just testing out * some features of Java. *

* @param args Contains the command line arguments. */ public static void main(String[] args) { // Create a list. List integerList = new ArrayList(); // Create data to store in the list. Integer val1 = new Integer(3); Integer val2 = new Integer(10); String str1 = new String( "Hello World!" ); String str2 = new String( "CS2334" ); // Add the data to the list. Notice we can mix the data // types that we put into the list. This can cause problems // if we are not careful. integerList.add( val1 ); integerList.add( val2 ); integerList.add( str1 ); integerList.add( str2 ); // Print the list. ListIterator itr = integerList.listIterator(); System.out.println( "Contents of the list:" ); while( itr.hasNext() ) { System.out.println( itr.next() ); } // Increment the value of each integer in the list. itr = integerList.listIterator(); while( itr.hasNext() ) { //itr.next(); // Here we should be doing something to list elements // The following will not compile because the system // thinks that the element returned by next() is of // type Object. It does not know that it should // be of type Integer. //itr.set( itr.next().intValue() + 1 ); // This code will give a run time class cast exception //Integer i = (Integer)itr.next(); //itr.set( new Integer( i.intValue() + 1 ) ); // This code will work without errors. Object obj = itr.next(); if( obj instanceof Integer ) { Integer j = (Integer)obj; itr.set( new Integer( j.intValue() + 1 ) ); } } // Print the list. itr = integerList.listIterator(); System.out.println( "Contents of the list:" ); while( itr.hasNext() ) { System.out.println( itr.next() ); } } }