Vector v = new Vector<Integer>(); //Line 1 v.add(1); v.add(2); v.add(3);
for(int i: v) //Line 2 System.out.print(i);
The above code will not compile as 'v' returns an Object which cannot be cast to an int or Integer on line 2.
If line 1 was changed to Vector<Integer> v = new Vector(); or Vector<Integer> v = new Vector<Integer>(); the code will work.
Can anyone explain why Vector v = new Vector<Integer>(); returns an object as i believed since v is set to <Integer> it should return an Integer object?
Vector v declares a variable 'v' that has the type Vector (not Vector<Integer>). The compiler treats this as any other legacy (pre-generics) Vector, so anything you get anything out of 'v' will be a reference of type Object, and you need to explicitly downcast to the actual type.
When you declare the variable using generics, Vector<Integer> v, this tells the compiler that it needs to do some extra work. In this case, when you get something out of 'v' the compiler knows that it's (supposed to be) an Integer, and it inserts the downcast for you behind the scenes.
(Edit: Disabled smilies.) [ November 05, 2008: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Originally posted by suresh pilakal babu: ...I mean both Vector<Integer> v = new Vector<Integer>(); and Vector<Integer> v = new Vector(); are same? ...
When you try to compile these, you will see the difference.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org