Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Convert int array to Vector

 
Rohit Bhagwat
Ranch Hand
Posts: 205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
System.out.println((String)l.get(0));
System.out.println((String)l.get(1));

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
Rohit.
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
 
Rohit Bhagwat
Ranch Hand
Posts: 205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rohit.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic