我有一个 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
有谁知道如何获取二维数组特定位置的索引? (索引是随机的)。如果您有任何疑问,请告诉我。谢谢!
最佳答案
您不能直接检索索引,因为索引用于访问 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;
}
}
然后将其传递给原始对象。
但是,如果您不需要将它们逻辑地放在 2D 数组中,此时您可以只使用包装器,而不使用任何 2D 数组。
关于java - 获取 ArrayList 中二维数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16431182/