Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

problem in vector

 
Preeti Sikri
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
add.addElement(4);
add.addElement(3);

int size=add.size();

for(int i=0;i<size;i++)>
{
int bookid = add.elementAt(i);
system.out.println()bookid;
}
I know this is very basic pls tell me how to solve this problem
Thanks in advance
Preeti
 
Bruce Wingate
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Bruce.
 
Eric Edwards
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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));

while(e.hasMoreElements())
{
Double o = (Double)e.nextElement();
double i = o.doubleValue();
System.out.println((i * 2));
}
}
}
 
Geoff Tate
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic