Two Laptop Bag
The moose likes Beginning Java and the fly likes problem in vector Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "problem in vector" Watch "problem in vector" New topic

problem in vector

Preeti Sikri
Ranch Hand

Joined: Mar 01, 2001
Posts: 30
hi there
Actually I have a vector in which I have stored some id(which r integer) now I want to assign those int to a variable called bookid but when I try to do that it give me error :
" Incompatible type for declaration. Can't convert java.lang.Object to int.
int bookid = add.elementAt(i); "

my code is
Vector add = new Vector();

int size=add.size();

for(int i=0;i<size;i++)>
int bookid = add.elementAt(i);
I know this is very basic pls tell me how to solve this problem
Thanks in advance
Bruce Wingate
Ranch Hand

Joined: Feb 16, 2001
Posts: 32
Vectors hold Objects, and oddly, the integer type is not an object. You can get around this by using the class Integer and then casting it to int. You might be able to cast it explicity from Object to int.
Eric Edwards
Ranch Hand

Joined: Feb 12, 2000
Posts: 60
Try this. I wrote this program to store a Double, but you can easily change it to an Integer to suit your needs. Notice the casting at the end.
Hope this helps.
import java.util.*;
public class VectorDouble
public static void main(String[] args)
Vector v = new Vector();
Enumeration e = v.elements();

for(int i = 0; i < 10; i++)
v.addElement(new Double(i * 1.2));

Double o = (Double)e.nextElement();
double i = o.doubleValue();
System.out.println((i * 2));
Geoff Tate
Ranch Hand

Joined: Feb 06, 2001
Posts: 55
Vectors hold only the Object type, so you must use anything that is a subclass of Object, which every class descends from. int is a primitive type, however for all primitive types there are wrapper objects. in this case the wrapper object would be Integer. Now, since vectors only store objects you can call vector.addElement(Integer) and the compiler will coerce the Integer reference to an Object reference without any programmer intervention. However, when you try to retreive an element from the vector you must explicity cast the element back to its a class that is compatabile to what you are going to assign it the element to:
Integer i = (Integer)e.nextElement();
This saves the programmer from having to create different vectors for each object type. And vectors can hold different objects within them. element 0 could be an Integer and element 1 could be a String.
[This message has been edited by Geoff Tate (edited March 06, 2001).]

<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR> fantastic, a towel? <HR></BLOCKQUOTE>
I agree. Here's the link:
subject: problem in vector
It's not a secret anymore!