2013-03-28 44 views
-6

如何從這個轉換:如何從ArrayList <int[]>轉換爲int數組?

ArrayList<int[]> 

至 -

int[] 

private ArrayList<int[]> example = new ArrayList<int[]>(); 

private int[] example; 

例如ArrayList({1,2,3},{2,3,4}) to {1,2,3,2,3,4}

+0

你甚至嘗試什麼嗎? – SudoRahul 2013-03-28 03:00:39

+1

你想將列表列表組合成一個更大的列表?你有什麼嘗試? – 2013-03-28 03:00:40

+2

數組的列表?我沒有關注。 – squiguy 2013-03-28 03:01:03

回答

2

這個問題的(稍微)棘手的部分是,在開始之前,你必須弄清楚輸出數組需要多大。因此該解決方案是:

  1. 遍歷該列表求和數組的大小在列表
  2. 分配輸出數組
  3. 使用嵌套循環的整數複製到輸出陣列。

我不打算爲你編碼。你應該有能力自己編碼。如果不是,你需要得到能力 ...通過嘗試自己做。


如果輸入和輸出類型不同,可能會有更整潔的解決方案使用第三方庫。但是,您使用int[]的事實使您不太可能找到現有的庫來幫助您。

0

在這個快速食譜:從每個數組數的元素個數,創建一個數組保存所有的元素,複製元素:)

import java.util.ArrayList; 

// comentarios em pt-br 
public class SeuQueVcConsegue { 

    public static void main(String[] args) { 

     ArrayList<int[]> meusNumerosDaSorte = new ArrayList<int[]>(); 
     meusNumerosDaSorte.add(new int[]{1,2,3}); 
     meusNumerosDaSorte.add(new int[]{4,5,6}); 

     // conta os elementos 
     int contaTodosOsElementos = 0; 
     for(int[] foo : meusNumerosDaSorte){ 
      contaTodosOsElementos += foo.length; 
     } 

     // transfere os elementos 
     int[] destinoFinal = new int[contaTodosOsElementos]; 
     int ponteiro = 0; 
     for(int[] foo : meusNumerosDaSorte){ 
      for(int n : foo){ 
       destinoFinal[ponteiro] = n; 
       ponteiro ++; 
      } 
     } 

     // confere se esta correto :) 
     for(int n : destinoFinal){ 
      System.out.println(n); 
     } 

    } 
} 
相關問題