0

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++) {
            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 writting integer instead of int in enumeration?

user207421
  • 289,834
  • 37
  • 266
  • 440
Rajeev
  • 13
  • 2

1 Answers1

1

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.

Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399