2016-04-27 56 views
-1

我需要將arraylist的值放入數組中,以便我可以完成for-loop項目。我有一個陣列列表,有10個陣列列表,每個陣列都有一個或多個整數值:Arraylist<ArrayList<Integer>> lists = new ArrayList<>(); 我用一個for-loop創建了另外10個陣列,現在我需要將10個陣列列表放到一個陣列中,它是將幾個Arraylist轉換爲數組

Integer [] second; 

我需要把arraylist按照它們放置的順序放到[]數組中,我必須這樣做才能完成我的項目。但由於某種原因,我的for-loop用於將每個單一的數組列表放入數組中將不會打印它們。有什麼建議麼? 這裏是用來打印的ArrayList到陣列我的for循環:

for(int i=0; i<lists.siz();i++) 
{ 
    second = lists.get(i).toArray(second); 
} 
+0

'秒'未初始化。嘗試'toArray(new Integer [0])'。 – shmosel

回答

1
// Create temp list 
List<Integer> secondList = new ArrayList<Integer>(); 
// add all sublist to temp list 
for(ArrayList<Integer> subList : lists) 
{ 
    secondList.addAll(subList); 
} 
// convert temp list to array 
Integer[] second = secondList.toArray(new Integer[secondList.size()]); 
+0

非常感謝你! –

1

進口的java.util.ArrayList;

import org.apache.commons.lang3.RandomUtils;

公共類ArrayListToArray {

public static Integer[] IncreaseArraySizeByOneElement(Integer[] oldArray){ 
    int sizeOfOldArray=oldArray.length; 
    int newSizeOfArray=sizeOfOldArray+1; 
    Integer[] newArray=new Integer[newSizeOfArray]; 
    for(int x=0;x<sizeOfOldArray;x++){ 
     newArray[x]=oldArray[x]; 
    } 
    return newArray; 
} 

public static void main(String[] args) { 

    ArrayList<ArrayList<Integer>> ListOfIntArray = new ArrayList<ArrayList<Integer>>(); 
    for (int x = 0; x < 10; x++) { 
     ArrayList<Integer> ListOfInts = new ArrayList<Integer>(); 
     for (int y = 0; y < 5; y++) { 
      ListOfInts.add(RandomUtils.nextInt(4800, 7000)); 
     } 
     ListOfIntArray.add(ListOfInts); 
    } 

    System.out.println("There are 10 ArrayList containing each ArrayList 5 elements "+ListOfIntArray); 
    System.out.println("Let's put now above ArrayList of ArrayList into a single Integer[]"); 

    Integer[] arrayOfMyInts = null; 

    for (ArrayList<Integer> ListOfInts : ListOfIntArray) { 
     for (int y = 0; y < 5; y++) { 
      if(arrayOfMyInts==null){ 
       arrayOfMyInts = new Integer[0]; 
      } 
      arrayOfMyInts=ArrayListToArray.IncreaseArraySizeByOneElement(arrayOfMyInts); 
      arrayOfMyInts[arrayOfMyInts.length-1]=new Integer(ListOfInts.get(y)); 
     } 
    } 

    System.out.println("Printing all elements Integer[]"); 
    for(int x=0;x<arrayOfMyInts.length;x++) 
    System.out.println(arrayOfMyInts[x]); 
} 

}

+0

上面的代碼顯示了創建ArrayList類型爲Integer的arrayList,然後將它們放入單個整數數組中並打印輸出。我希望這對你有所幫助 – ramanuj