|
-
Feb 18th, 2001, 07:10 PM
#1
Thread Starter
Dazed Member
Can anyone tell me what i might be doing wrong with
this code??? I dont really have to much experience using vectors so im not quite sure how to go about this.
All i simply want to do is take each element of the hold
array and tranfer that into the vec vector. But i keep getting a inconvertable type error. When i try to cast.
thanks
import java.util.Vector;
class Vectortest{
public static void main(String[] args){
int[] hold = new int[25];
for(int i = 1; i < 25; i++){
hold[i] = i;
}
Vector vec = new Vector();
for(int i = 1; i < 25; i++){
vec.addElement((Vector)hold[i]);
}
}
}
-
Feb 19th, 2001, 12:31 AM
#2
The addElement method of class Vector takes an Object.
addElement(Object obj)
int is not a dataype of class Object. int is a primitive datatype.
There is an "Integer" class that "wraps" the primitive "int" datatype to be an object of class "Object".
Change
vec.addElement((Vector)hold[i]);
to
vec.addElement(new Integer(hold[i]));
Now when you write code to extract the Integer from the Vector, you need to cast the Vector element to (Integer). You know that there is an "Integer" at that element or you can test using "instanceof". Then you can use the method intValue() from the Integer class to get an int.
I suppose this is just for learning how to use the Vector class, because just using an int[] might be sufficient in a real application.
Note
Primitive arrays behave like Objects, so you can add the entire array hold with one addElement call without a loop.
Vector vec = new Vector();
vec.addElement(hold);
-
Feb 19th, 2001, 11:02 AM
#3
Thread Starter
Dazed Member
Hummmmmmm interesting.. But i thought java treats all
arays as objects regardless of what data type the
array actually is... I jst checked out the java.lang.Integer
class to see waht methods it contains. So by changing
vec.addElement((Vector)hold[i]);
to
vec.addElement(new Integer(hold[i]));
i am casting an integer array to a integer object class?
thanks again VirtuallyVB
-
Feb 19th, 2001, 12:40 PM
#4
hold[i] is an int
hold is an int array
hold is an Object
hold[i] is a primitive
Depending on what you are trying to accomplish, you can add the entire array (since it's an Object) in one call
vec.addElement(hold);
i am casting an integer array to a integer object class?
No.
That casts an int (not an int array) to an Integer object.
Because all objects inherit from Object, you can use the Integer object in the addElement method.
I am using the term object and Object as a general term and a type name respectively.
You are welcome 
Note: Technically, I shouldn't say "casts an int to an Integer", it's more like "wraps an int, making an Integer object".
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|