1

When I try to create an ArrayList myArrayList from an array, using Arrays.asList(myArray), I am not getting the List of elements in myArray. Instead I get list of Array.

The size of myArrayList is 1 . When I try to do myArrayList.toArray(), I am getting a two dimensional array. What to do to get the elements of myArray in a list? Is iterating the only option??

2
  • Looks like your myArray is a two dimensional array. Have you made sure there are no double braces like {{"one", "two"}}? Commented Sep 22, 2011 at 11:50
  • 1
    @bluish Sorry, I wasn't doing that. I will correct myself. Thanks. @ others Just as Banther said, I was trying it on an int[]. Next time onwards, I will try to post the code snippet. Thanks Commented Sep 22, 2011 at 12:16

5 Answers 5

3

Firstly, the asList method is the right method:

Integer[] myArray = new Integer[3];
List<Integer> myArrayList = Arrays.asList(myArray);
System.out.println(myArrayList.size()); // prints 3, as expected

The problem may be that you are calling the varargs asList method in such a way that java is interpreting your parameter as the first varargs value (and not as an array of values).

Object myArray = new Integer[3];
List<Object> myArrayList = Arrays.asList(myArray);
System.out.println(myArrayList.size()); // prints 1 - java invoked it as an array of Integer[]

To fix this problem, try casting your parameter as Object[] to force the varargs invocation, eg:

Object myArray = new Integer[3];
List<Object> myArrayList = Arrays.asList((Object[]) myArray); // Note cast here
System.out.println(myArrayList.size()); // prints 3, as desired
Sign up to request clarification or add additional context in comments.

Comments

2

What is the type of myArray? You cannot use Arrays.asList with an array of primitive type (such as int[]). You need to use loop in that case.

3 Comments

Thanks Banther. I was trying it for an int[] only.
@Suma this is why posting code in a question is a good idea. It would have reduced a lot of guesswork.
@JohnB yes, I understand now. Sorry:(
2

There are different ways by which you can achieve it.3 example of converting array to arraylist and arraylist to array in java might help.

Comments

1

Would this work?

Object[] myArray = new Object[4]; //change this to whatever object you have
ArrayList<Object> list = new ArrayList<Object>();
for (Object thing : myArray) list.add(thing);

Comments

0

Try providing the generic type in the method call. The following gives me a list of 2 String elements.

    String[] strings = new String[]{"1", "2"};
    List<String> list = Arrays.<String>asList(strings);
    System.out.println(list.size());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.