Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Is there any short combination to convert array of primitive to List & receive "printable" version?

Tags:

java

arrays

int[] arrc = new int[] {1, 2, 3};
System.out.println(new ArrayList(Arrays.asList(arrc)));

prints address, but i desire to use toString as in ArrayList.

Is it possible ?

like image 282
dmitrynikolaev Avatar asked Mar 30 '10 08:03

dmitrynikolaev


1 Answers

Try:

import java.util.Arrays;

// ...

int[] arrc = new int[] {1, 2, 3};
System.out.println(Arrays.toString(arrc));

Note that the asList(...) does not take an array of primitive int's but takes Objects instead, that's why you see an address-like String appear.

So, doing:

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

results in the same as doing:

int[] array = {1, 2, 3};
List list = new ArrayList();
list.add(array);

Both result in a List that has one element in it: an array of primitive ints.

(only that Arrays.asList(...) returns a List that cannot be modified...)

like image 137
Bart Kiers Avatar answered Oct 05 '22 19:10

Bart Kiers