I have a vector in which I added some integer numbers. Now when I remove these numbers from the vector and try to store it in an int variable I am getting "Incompatible types..found int ,expected java.lang.object". Any suggestions how can I store the values in a vector in a variable.

Vector neig = new Vector();
    int x = neig.get(1); //error here
7 Years
Discussion Span
Last Post by jon.kiparsky

When you create a Vector without a type, it's automatically a Vector<Object> - that is, when you get() something from the vector, all the compiler knows is that it's an Object.

When you add() your ints, they're auto-boxed into Integers, which are of course Objects. Fine so far. When you get() them, though, they can't be auto-unboxed because to the compiler, they're not Integers, they're Objects.
You can cast them, if you want:

int x = (Integer)neig.get(1);

but what you're doing here is ignoring the wonderful world of Generics. If you really want to store your ints in a Vector, declare your Vector to be a Vector of Integers:

Vector<Integer> neig = new Vector<Integer>()

and the rest of the code should work fine.

Bear in mind, though, that you're paying a performance penalty for the autoconversion each time you add and get an int, and it might be better in terms of performance to use an array of ints.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.