vector

M

mehmet canayaz

how can I create a vector with size of 10 which
saves only int values??
how can I specify that the vector will only have int values??

thanks

mehmet canayaz
 
O

Oliver Wong

mehmet canayaz said:
how can I create a vector with size of 10 which
saves only int values??
how can I specify that the vector will only have int values??

If you're using Java 1.5, you can use generics to accomplish this. If
you're using an earlier version of Java, you can't.

The syntax looks like this:

Vector<Integer> myVectorOfInts = new Vector<Integer>(10);

Note that actually, the vector is specified to only contain Integer
objects (or subclasses of Integer). You can't actually put primitive types,
such as "int" in a Vector. Trying to do so will result in boxing and
unboxing, where the int will automatically get converted to an Integer as
needed.

- Oliver
 
M

mehmet canayaz

If you're using Java 1.5, you can use generics to accomplish this.

what do you mean??
 
M

mehmet canayaz

I have a vector which saves the user input and I want to threat the
elements of the vector
as integers. but I cannot cast like
int u = (int) vec.elementAt(i)

or can I do it?
 
C

Carl

mehmet said:
I have a vector which saves the user input and I want to threat the
elements of the vector
as integers. but I cannot cast like
int u = (int) vec.elementAt(i)

or can I do it?

When casting an element of a Vector, remember that Vectors contain
objects (i.e. java.lang.Integer) not primitive data types (like int).

Hope that helps,
Carl.
 
R

Roedy Green

If you're using Java 1.5, you can use generics to accomplish this. If
you're using an earlier version of Java, you can't.
You could do it in an older version by extending Vector and creating
new add methods. You could also use a somewhat cheating technique of
throwing an exception if the objects added were the wrong type, using
the existing method signatures. You could also create new get methods
with a built-in cast. By the time you have done all that, you might
as well implement your own Vector with ant internal int[] array.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,678
Members
48,796
Latest member
Greg L.

Latest Threads

Top