0

I am new to Java so can someone please explain why are we declaring the variable in such way for Enumeration. I get that some sort of Unboxing is happening here but I am having kind of difficulty understanding this. I am specifically talking about [[ double y=(Double) ]] from the code. Any help is appreciated. Thank you.

import java.util.Enumeration;
import java.util.Vector;

public class EnumarationDemo {

    public static void main(String[] args) {
        
        Vector v  = new Vector();
        for(int i=0; i<=5; i++) {
            v.addElement(i);
        }
                System.out.println(v);  
    
    Enumeration e= v.elements();
    while(e.hasMoreElements()) {
        double y=(Double) e.nextElement();
        if(y%2==0) {
            System.out.println(y);
        }
    }
    
    }
}
Turing85
  • 18,217
  • 7
  • 33
  • 58
  • 3
    If you're new to Java, then be aware that `Enumeration` and `Vector` have been obsolete since 1998. Use `List` and Iterator` instead, and you should be using generics (`` for every type listed); you're getting warnings and should pay attention to them. – chrylis -cautiouslyoptimistic- Sep 23 '20 at 22:03
  • Thank you for the information. This is one of my class assignment on Collection framework that is why I was going through it. – iamaskingaquestion Sep 23 '20 at 22:09
  • Please also read: [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/q/2770321/5221149) --- Since you don't seem to be understanding the code, it's obvious that you didn't write it, so I strongly suggest that you grab the book where you found this example and **BURN** it in effigy, because that is the sorriest excuse for *ancient* Java code I've seen in a very, VERY long time. Find yourself some better teaching material. Shouldn't be difficult, because it can hardly be worse. – Andreas Sep 23 '20 at 22:18
  • Do you know about java generic? `Vector` and `Enumeration` has a type parameter let you specify the type it stores. You should declare `Vector` and `Enumeration` to avoid the casting. – haoyu wang Sep 24 '20 at 03:29

0 Answers0