I was trying my hands on vectors and wrote a simple code to access its elements through enumeration.
Vector v = new Vector();
v.add("Some String");
v.add(10);
Enumeration e = v.elements();
while(e.hasMoreElements()) System.out.println(e.nextElement());
Working with raw types produces results as expected(prints the elements). But, when I use generic type of enumerator, it gets tricky.
With String as type parameter:
Vector v = new Vector();
v.add("Some String");
v.add(10);
Enumeration<String> e = v.elements();
while(e.hasMoreElements()) System.out.println(e.nextElement());
Output:
Some String
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
With Integer as type parameter:
Vector v = new Vector();
v.add("Some String");
v.add(10);
Enumeration<Integer> e = v.elements();
while(e.hasMoreElements()) System.out.println(e.nextElement());
Output:
Some String
10
What is happening here? Shouldn't both the cases produce ClassCast exception?