converting array into arraylist
Currently i have:
Code java:
int[] test = {1,2,3,4,5};
ArrayList<Integer> ar = new ArrayList<Integer>(Arrays.asList(test));
this gives me the error:
Code :
error: no suitable constructor found for ArrayList(List<int[]>)
ArrayList<Integer> ar = new ArrayList<Integer>(Arrays.asList(test));
^
constructor ArrayList.ArrayList(Collection<? extends Integer>) is not applicable
(actual argument List<int[]> cannot be converted to Collection<? extends Integer> by method invocation conversion)
constructor ArrayList.ArrayList() is not applicable
(actual and formal argument lists differ in length)
constructor ArrayList.ArrayList(int) is not applicable
(actual argument List<int[]> cannot be converted to int by method invocation conversion)
1 error
What i want to do is make a method that takes an array as parameter and returns an arraylist with the same elements.
Re: converting array into arraylist
See the API for Arrays.asList...it accepts an array of objects - not primitives (in many cases the compiler is smart enough to interchange through something called autoboxing - in this case not). Using a simple loop you can add the items of the array to the List.
Re: converting array into arraylist
Re: converting array into arraylist
Create the method yourself. Just iterate through the array and return the elements in a new list.
Code Java:
public ArrayList<T> arrayToArrayList(<T> array)
{
ArrayList<T> list = new ArrayList<T>();
for(int i=0; i<array.length; i++)
list.add(array[i]);
return list;
}
Re: converting array into arraylist
Quote:
Originally Posted by
Harry Blargle
What i want to do is make a method that takes an array as parameter and returns an arraylist with the same elements.
Then do what kenster421 said. Iterate through the array and add it all to the ArrayList.
One small fix though. Make the parameter an "E" array. (E[] array)
Code :
public ArrayList<E> test(E[] array) {
//Iterating code
}
Be careful when using generic types with plain arrays though. They hold primitives as well as objects, which can cause problems.
Re: converting array into arraylist
Quote:
Originally Posted by
bgroenks96
Then do what kenster421 said. Iterate through the array and add it all to the ArrayList.
One small fix though. Make the parameter an "E" array. (E[] array)
Code :
public ArrayList<E> test(E[] array) {
//Iterating code
}
Be careful when using generic types with plain arrays though. They hold primitives as well as objects, which can cause problems.
Whoops, thanks for the clarification.
Re: converting array into arraylist
Hi,
You have to use:
Integer[] test for this.
bean factory