File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Convert int array to Vector Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Convert int array to Vector" Watch "Convert int array to Vector" New topic

Convert int array to Vector

Rohit Bhagwat
Ranch Hand

Joined: Dec 19, 2004
Posts: 205
Hello friends,sir,madam

I want to convert int array to Vector. i.e all elements of int array should become the elements of Vector.

I need to accomplish this without using loops.

Here is an Example of String array

String[] str={"A","B","C"};
List l=Arrays.asList(str);

So here I directly convert a String array to vector without using loops.
But since Vectors are capable of storing objects I am stuck if I use int array instead of String array.

I want to know is there any std method to do this. Thats the only moto for not using loops.

Does anyone have any idea how can I do this ?

Your suggestions will be highly appreciable.

Waiting for your reply
Thanks and Regards
Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

Is there any reason you need to use Vectors? If not, an ArrayList might be better.

None of the Collection implementations can store primitives directly, but all primitives have wrapper classes. So you can store Integers instead of ints.

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

In Tiger (JDK 1.5), the following compiles, but does the wrong thing:

int[] array = { 0, 1, 2 };
List list = Arrays.asList(array);

The list ends up with "array" as its only member due to the varargs mechanism. But because of autoboxing and varargs together, this actually works, and gives you a list of Integer objects:

List list = Arrays.asList(1, 2, 3);

[Jess in Action][AskingGoodQuestions]
Rohit Bhagwat
Ranch Hand

Joined: Dec 19, 2004
Posts: 205
Thankyou all for posting your valuable suggestions..

I dont have any problem using ArrayList instead of vector , but I want integer objects in the list which i was not getting. So may be 1.5 has come out with it..

Thanks and Regards
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
If you are stuck with receiving an int array, you can't avoid iterating over it when putting them into a Collection, including ArrayList. Even if Java provided some syntactic sugar via autoboxing, it would still involve iterating the array, autoboxing each int and adding it to the List one by one. All you'd save is a little typing.
I agree. Here's the link:
subject: Convert int array to Vector
It's not a secret anymore!