public class ProblemBeforeGenerics
1: //ProblemBeforeGenerics.java
3: import java.util.ArrayList;
4: import java.util.List;
5: import java.util.Date;
7: public class ProblemBeforeGenerics
8: {
9: public static void main(String[] args)
10: {
11: List myList = new ArrayList();
12: myList.add(new Date());
13: myList.add(new String("Hello, world!"));
14: myList.add(Integer.valueOf(6));
15: System.out.println((Date)myList.get(0));
16: System.out.println((String)myList.get(1));
17: System.out.println((Integer)myList.get(2));
19: //The following code snippet illustrates the problem
20: //that Java had before generics ... you could add an
21: //object of any kind to a container, so you had to know
22: //what was stored where and make the appropriate cast
23: //when retrieving an object from the container. This
24: //code snippet compiles without any problem, but causes
25: //a runtime exception because of the incorrect cast.
26: //It is much better to catch such problems at compile time!
28: //myList.add(new String("So long!"));
29: //System.out.println((Integer)myList.get(3));
30: }
31: }
32: /* Output:
33: Thu Jul 26 16:31:25 ADT 2018
34: Hello, world!
35: 6
36: */