2017-09-04 130 views
-1

如何從ArrayList<long[]>中檢索元素?如何從包含長數組的ArrayList中檢索元素

我寫這樣的:

ArrayList<long []> dp=new ArrayList<>(); 

//m is no of rows in Arraylist 
for(int i=0;i<m;i++){ 
    dp.add(new long[n]); //n is length of each long array 
    //so I created array of m row n column 
} 

現在,如何讓每一個元素?

+0

'dp.get(someIndex)some_other_index]'? –

+2

請添加適當的語言標籤。數組列表是多種編程語言的一部分。 – reporter

+0

無語言無回答 –

回答

0

在該列表中的每一個元素是一個數組...所以你需要那些認真補充: 使用匿名數組new long[] { 1L, 2L, 3L } 或使用new關鍵字new long[5]

public static void main(String[] args) throws Exception { 
    ArrayList<long[]> dp = new ArrayList<>(); 
    // add 3 arrays 
    for (int i = 0; i < 3; i++) { 
     dp.add(new long[] { 1L, 2L, 3L }); 
    } 
    // add a new array of size 5 
    dp.add(new long[5]); //all are by defaul 0 
    // get the info from array 
    for (long[] ls : dp) { 
     for (long l : ls) { 
      System.out.println("long:" + l); 
     } 
     System.out.println("next element in the list"); 
    } 
} 
+1

您是否願意將適當的語言標記添加到問題中?看起來你知道這種語言(看起來像Java)。謝謝。 – reporter

-1

你也可以有especifying大小一個ArrayList的objetcs,裏面包含一個long數組。但到目前爲止,您的代碼的問題是,您沒有在每個長數組中放入任何值。

public class NewClass { 

    private static class MyObject { 
     private long []v; 

     public MyObject(int n) { 
      v = new long[n]; 
     } 

     @Override 
     public String toString() { 
      String x = ""; 

      for (int i = 0; i < v.length; i++) { 
       x += v[i] + " "; 
      } 
      return x; 
     } 
    } 

    public static void main(String[] args) { 
     ArrayList<MyObject> dp = new ArrayList(); 
     int m = 3; 
     int n = 5; 

     for (int i = 0; i < m; i++) { 
      dp.add(new MyObject(n)); 
     } 

     for (MyObject ls : dp) { 
      System.out.println(ls); 
     } 
    } 
} 
0

你可以像從ArrayList獲得任何東西一樣獲得數組。例如,爲了獲取存儲在ArrayList第十long[],你會使用get方法:

long[] tenthArray = dp.get(9); 
+0

得到第10行中的第8個元素寫爲 long l = dp.get(9)[7];一個dit的作品。謝謝 –

相關問題