2017-07-27 59 views
0

我需要建立一個ArrayListInteger在新的Array s在它。我如何設置和添加項目?Arraylist內陣列

private final ArrayList<Integer>[] test; 

test = new ArrayList<Integer>(); 

這是行不通的。
謝謝!

+0

你可以請詳細說明你的意思是什麼 - 的ArrayList整數在新的數組呢? – ayush

+0

'測試'Arraylist的元素又是一個整數的數組..你正在說什麼? – ayush

+0

我想設置一個數組列表,並且數組列表中的對象是具有整數的數組。我不知道如何設置這個Arraylist。一個正常的ArrayList不是一個問題。那麼我怎麼能初始化ArrayList,然後添加Integer數組? – valenth

回答

0

看起來像你想創建一個2 dimansional整數數組。

我假設你有一個特殊的用例,在這個用例中你需要一個基本數組obobarList-Objects。

不管怎麼說,你可以創建像任何其他原始陣列 這樣的事情像

ArrayList<Integer>[] test = new ArrayList[2]; 

和接入/按索引設置..

test[0] = new ArrayList<Integer>(); 

您也可以填寫在初始化數組...

ArrayList<Integer>[] test = new ArrayList[] { 
     new ArrayList<Integer>(), 
     new ArrayList<Integer>(), 
     new ArrayList<Integer>() 
}; 
0

如果我們想ArraysList然後 -

class Test { 

    private final List<int[]> myList; 

    public Test() { 
     myList = new ArrayList<>(); 
    } 

    public void add(int[] myArray) { 
    myList.add(myArray); 
    } 
} 

你總是允許初始化最終的變數。編譯器確保你只能做一次。

+0

它是不允許更改私人「最終ArrayList []測試;」,所以我必須建立它與這些規範。只需要知道如何初始化這些。謝謝 – valenth

+0

你可以初始化最後一個變量.. – ayush

+1

檢查修改後的答案once..also我想你應該閱讀關於java中的final關鍵字。 – ayush

2

數組是一個Object,你可以做任何對象類型名單 - 這樣就可以使陣列的List沒有做什麼特別的東西:

// Declare it and initialise as an empty list 
List<Integer[]> list = new ArrayList<>(); 

// Add an item -- it's a new array 
list.add(new Integer[5]); 

// Access an item -- it's an array 
Integer[] array = list.get(0); 
Integer x = array[0]; 

我看到使用的陣列幾個原因然而,在大多數情況下,我們需要使用Integer。一組int也是Object,所以你可以使用它。

List<int[]> list = new ArrayList<>(); 
list.add(new int[5]); 

一個使用對象Integer,而不是原始int最常見的原因是,你不能有List小號原語。但你可以有原始數組,所以如果你對數組較小的表達力量感到滿意,通過所有的方式來填充原語。

問自己,爲什麼你想要的陣列,而不是ListList一個S,數組的數組或List秒的陣列的List,但是。你的問題要求「數組列表中的數組」。

List<Integer[]>是數組列表(因爲在<>內部是Integer[])。

List<Integer>[]是一個列表數組 - 「陣列內的ArrayList」 - 因爲[]List<>聲明之後。

您可以初始化你的列表的陣列,就像任何其他數組,new Type[length]

// Declare it 
List<Integer>[] array = new List<Integer>[5]; 

// Put something into an array element 
array[3] = new ArrayList<Integer>(); 

// Access an element -- it's a List 
List<Integer> list = array[3]; 
Integer x = list.get(0); 
+0

嗨,我不允許改變這段代碼:private final ArrayList [] test; - >那麼你能初始化這段代碼嗎? ArrayList和[]在鑽石算子之外。在你的代碼中,[]在鑽石操作員中。 – valenth

+0

valenth - 'ArrayList []'是列表數組,而不是數組列表。將添加一些答案。 – slim

0

u可以使用這樣做到這一點的

private ArrayList<Integer>[] test ; 

private void test(int n){ 
    test=new ArrayList[n]; 
    for(int i=0;i<n;i++){ 
     test[i]=new ArrayList<Integer>(); 

     test[i].add(100); 
     test[i].add(10); 
     test[i].add(10000); 
     test[i].add(1); 
     .... 
    } 
}