2015-11-08 80 views
1

我在从阵列转换的问题以ArrayList的从int数组转换为整数数组列表中的java

public class one 
{ 
public static void main(String args[]) 
{ 
int y[]={12,25,38,46}; 
two p=new two(); 
p.setLocations(y); 
} 
} 


import java.io.*; 
import java.util.*; 

public class two 
{ 
    ArrayList<Integer> data_array=new ArrayList<Integer>(); 


void setLocations(int locations[]) 
{ 
     ArrayList<Integer> locations_arraylist=new ArrayList(Arrays.asList(locations)); 
     data_array=locations_arraylist; 
    for(int i=0;i<data_array.size();i++) 
     System.out.println("data_array["+i+"]="+data_array.get(i)); 
} 
} 

在下面的线

ArrayList<Integer> locations_arraylist=new ArrayList(Arrays.asList(locations)); 
//Copying from array to ArrayList-Its converting,Please suggest 
+0

什么是'位置':'int'的数组**或**'ArrayList '?请下定决心。 –

+0

@ Eng.Fouad“locations”是一个int数组,我需要将int的位置转换为ArrayList – VijayIndia

回答

1

int[]是从List<Integer>完全不同。例如,Integer有标识,以及一个值。没有简单的转换方法。

以下方式处理Java 8

int[] array = {1, 2, 3, 4, 5}; 
List<Integer> list = IntStream.of(array).boxed().collect(Collectors.toCollection(ArrayList::new)); 

的工作原理如下早期版本。

int[] array = {1, 2, 3, 4, 5}; 
List<Integer> list = new ArrayList<Integer>(); 
for (int a : array) 
    list.add(a); 

如果你传递一个int[]Arrays.asList你得到一个List<int[]>,而不是一个List<Integer>

0

建议使用成员的接口List /变量和使用ArrayList构造。此外ArrayList没有括号指明原始类型,而不是代替通用的。

如果你想避免一个for循环,将值从数组复制到List,有2个解决方案:

  1. 番石榴(放在上面import com.google.common.primitives.Ints;

    List<Integer> locations_arraylist = Ints.asList(locations); 
    
  2. 直接将值传递给Arrays.asList()

    List<Integer> locations_arraylist = Arrays.asList(12, 25, 38, 46); 
    
0

你可以试试这个:

更换int y[]={12,25,38,46};Integer y[] = {12, 25, 38, 46};
不需此行,以及
ArrayList<Integer> data_array = new ArrayList<Integer>();
您可以使用for-each循环打印数组:

int i=0; 
     for (Integer locations_arraylist1 : locations_arraylist) { 
      System.out.println("data_array[" + i + "]=" + locations_arraylist1); 
      i++; 
     } 
+0

'setLocations(Integer locations [])'也应该是一个Integer数组参数。 –

+0

我需要扩展我的课程,并且需要在未来执行添加和删除选项。 – VijayIndia

+0

那么它是更好地去与“保罗博丁顿答案。他在那里使用了一个列表来解决他的问题。我只是试图做出最小的修复并使代码工作。 :) –

0

试试这个:

int[] arrayInt = new int[]{1, 2, 3}; 
List<Integer> list = Arrays.asList(ArrayUtils.toObject(arrayInt));