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
Joined: Feb 16, 2001
Posts: 32
posted
0
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
Joined: Feb 12, 2000
Posts: 60
posted
0
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
Joined: Feb 06, 2001
Posts: 55
posted
0
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: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.