2013-05-10 103 views
0

我有2号的int数组。 余万这个数字复制到数组列表,并打印出来。尽可能避免使用Integer结果[];Copystored数组值到数组列表JAVA

int result[] = {1024,2048}; 
    List<Integer> res = new ArrayList<Integer>(result); 


public class TEA { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 

      int result[] = {1024,2048}; 
      List<int[]> res = Arrays.asList(result); 
      System.out.println(res); 


    } 

} 

output :[[[email protected]]

回答

1

如果你不能让resultInteger[],而不是一个int[],你的选择是要么做一个明确的for循环:

List<Integer> list = new ArrayList<Integer>(); 
for (int value : array) { 
    list.add(value); 
} 

...或者,如果你可以使用第三第三方库,使用番石榴的Ints.asList(int[])。这或多或少是您选择的整个空间。

+0

这是在新的值中添加,所以不能复制已有的阵列,而无需使用整数结果[]? – newbieprogrammer 2013-05-10 16:59:28

+0

...我不确定你在说什么。这些,如果你想获得一个'INT []'的'名单',但目前还不清楚你的意思是什么本质上是唯一的选择,“这是在新的增值。” – 2013-05-10 17:02:21

+0

哦,我得到了it..thanks 附:刚才看到了错误的代码。 – newbieprogrammer 2013-05-10 17:17:21

0

使用Arrays.asList()方法做同样的。

List<Integer> res = Arrays.asList(result); 

这是数组的列表视图,不能添加或删除元素。

List<Integer> res = new ArrayList<Integer>(Arrays.asList(result)); 

将源数组中的所有元素复制到新列表中。

EDITED:

有一个从原始类型的阵列没有自动转换到它们的包装引用类型的阵列。

int result[] = {1024,2048}; 
List<Integer> list = new ArrayList<Integer>(); 
for (int value : result) { 
    list.add(value); 
} 
System.out.println(list); 
+0

不工作的这两个......我得到错误,我也厌倦了不断变化的整数为int [],它返回一些垃圾值 – newbieprogrammer 2013-05-10 16:45:06

+0

什么错误????? – NINCOMPOOP 2013-05-10 16:45:59

+0

异常在线程“主要” java.lang.Error的:未解决的问题,编译: \t类型不匹配:不能从列表转换到列表 \t在TEA.main(TEA.java:74) – newbieprogrammer 2013-05-10 16:46:40