Rajeev Rajeev - 10 months ago 38
Java Question

why are we writting integer instead of int in enumeration?

This question is different according to situation, the question for which you marked my question as duplicate doesn't completely clarify my question situation answer.

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++) {
Enumeration enumeration = vector.elements();
while (enumeration.hasMoreElements()) {
Integer integer = (Integer) enumeration.nextElement();

why are we writting 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.