2015-11-08 87 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));