2013-05-08 101 views
0

我有一個ArrayList填充2D數組中的對象。我想要在ArrayList的索引處獲取二維數組中對象的索引。例如:獲取ArrayList中二維數組的索引

Object map[][] = new Object[2][2]; 
map[0][0] = Object a; 
map[0][1] = Object b; 
map[1][0] = Object c; 
map[1][1] = Object d; 

List<Object> key = new ArrayList<Object>(); 
key.add(map[0][0]); 
key.add(map[0][1]); 
key.add(map[1][0]); 
key.add(map[1][1]); 

我想要做的是:

getIndexOf(key.get(0)); //I am trying to get a return of 0 and 0 in this instance, but this is obviously not going to work 

有誰知道我可以在特定位置獲得二維數組的索引? (索引是隨機的)。如果您有任何問題,請告訴我。謝謝!

回答

3

僅僅因爲索引用於訪問map中的元素,但不包含在對象中,您不能直接檢索索引。對象本身沒有線索在數組內。

一個更好的方法是將存儲對象本身內部的指標:

class MyObject { 
    final public int x, y; 

    MyObject(int x, int y) { 
    this.x = x; 
    this.y = y; 
    } 
} 

public place(MyObject o) { 
    map[o.x][o.y] = object; 
} 

你甚至可以有一個包裝類,它可以作爲一個通用持有者:

class ObjectHolder<T> { 
    public T data; 
    public final int x, y; 

    ObjectHolder(int x, int y, T data) { 
    this.data = data; 
    this.x = x; 
    this.y = y; 
    } 
} 

,然後就通過這周圍而不是原來的對象。

但是,如果您不需要將它們邏輯地放在二維數組中,那麼此時您可以使用不包含任何二維數組的包裝。

+0

darn!以及我會用你的建議,謝謝! – Evorlor 2013-05-08 01:31:48