开发者

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

int[] arrc = new int[] {1, 2, 3};
System.out.println(ne开发者_Python百科w ArrayList(Arrays.asList(arrc)));

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

Is it possible ?


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...)


If you just want to print the array:

Arrays.toString( arrc )

If you want to turn an int[] into a List, Arrays.asList does not work, unfortunately (it only works with Object[]):

List<Integer> list = new ArrayList<Integer>(arrc.length);
for (int a: arrc)
   list.add(a);

System.out.println(list); // prints nicely now


use Arrays.toString(arrc)


Use Apache Commons Lang as your main library after SDK

System.out.println("An object: " + ReflectionToStringBuilder.toString(anObject));


using Dollar should be simple:

int[] ary = { 1, 2, 3, 4};
String string = $(ary).toString(); // wrapping Arrays.toString()

alternatively you can convert the int array to List then use the toString method :

List<Integer> list = $(ary).toList(); 

please note that list is an ArrayList: you can even specify which concrete class should be used simply passing a List implementation (it will work with any List implementation with a no-args constructor):

List<Integer> linkedList = $(ary).toList(LinkedList.class);


Using Ints.asList from Guava:

import java.util.List;
import com.google.common.primitives.Ints;

// ...

int[] arrc = {1, 2, 3, 4};
List<Integer> list = Ints.asList(arrc);
System.out.println(list);
// Output: "[1, 2, 3, 4]"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜