This question is different according to situation, the question for which you marked my question as duplicate doesn't completely answer my question.
import java.util.Enumeration; import java.util.Vector;
public class EnumerationDemo {
public static void main(String[] args) {
Vector vector = new Vector();
for (int item = 1; item <= 5; item++) {
vector.addElement(item);
}
System.out.println(vector);
Enumeration enumeration = vector.elements();
while (enumeration.hasMoreElements()) {
Integer integer = (Integer) enumeration.nextElement();
System.out.println(integer);
}
}
}
Why are we writing integer
instead of int
in enumeration?
You are allowed to write int
instead of Integer
, like this:
int integer = (Integer) enumeration.nextElement();
This compiles and runs on Java version 5 or later due to autoboxing/unboxing (demo).
The reason you need to do a cast to Integer
, not int
, is that Java treats primitive types separately from Object
-derived reference types, making it impossible to store primitives in standard Java collections without wrapping them in their Object
-derived equivalent.