2012-04-23 22 views
1

我有以下問題。java中arraylist的處理部分

我有一個矩陣W大的行和列的尺寸。各行的代表特徵值(填充有雙值)。而矩陣consturcted爲:

Hashmap<Integer,Arraylist<Double>> W = new Hashmap<Integer,Arraylist<Double>>(); 

同時使計算,我需要採取每一行的某些部分和在矩陣更新它們。我找了subList方法Arraylist。但問題是 它返回只有列表中,但我需要arraylist.Because的很多,我已經實施了取作爲參數的方法。那麼這種情況下的解決方案是什麼?

w1 = [1,3 ,4,6,9,1,34,5,21,5,2,5,1] 
w11 = [1,3,4] 
w11 = w11 +1 = [2,4,5] 
This changes w1 to = [2,4 ,5,6,9,1,34,5,21,5,2,5,1] 

回答

5

我找了子列表方法Arraylist.But問題是它只返回列表,但我需要的ArrayList中

這不是在所有問題。實際上,只要有可能,您應該更改代碼以使用List

A List是具體類型如ArrayList實現的接口。以下是完全合法:

List<String> list = new ArrayList<String>(); 
list.add("hello"); 
list.add("world"); 

我建議改變你的W這樣:

Hashmap<Integer, List<Double>> W = new Hashmap<Integer, List<Double>>(); 
+0

+1。事實上,除非明確需要'ArrayList'的某些功能,否則始終建議使用泛型類作爲參數。 – Tudor 2012-04-23 15:46:57

+0

其實我在**的大部分地方都使用** Arraylist **。改變會像從零開始:( – thetna 2012-04-23 15:47:25

+2

你可以永遠做'新的ArrayList(名單)'或者你甚至可以類型轉換,但我不推薦這種做法 – adarshr 2012-04-23 15:48:33

1

你可以繼承ArrayList提供的另一ArrayList切片的視圖。像這樣:

class ArrayListSlice<E> extends ArrayList<E> { 
    private ArrayList<E> backing_list; 
    private int start_idx; 
    private int len; 
    ArrayListSlice(ArrayList<E> backing_list, int start_idx, int len) { 
    this.backing_list = backing_list; 
    this.start_idx = start_idx; 
    this.len = len; 
    } 
    public E get(int index) { 
    if (index < 0 || idx >= len) throw new IndexOutOfBoundsException(); 
    return backing_list.get(start_idx + index); 
    } 
    ... set, others? ... 
} 

然後你可以做w11 = new ArrayListSlice<Double>(w1, 0, 3)。在w11任何操作都將出現在w1,假設你正確實現set

你可能會需要實現的ArrayList的大部分方法,使這項工作。如果他們只依靠其他人,有些人可能會工作,但很難從規範中知道。