【问题标题】:Get Index of 2D Array in an ArrayList获取 ArrayList 中二维数组的索引
【发布时间】:2025-12-31 10:10:16
【问题描述】:

我有一个 ArrayList,其中填充了 2D 数组中的对象。我想在 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

有谁知道如何在特定位置获取二维数组的索引? (索引是随机的)。如果您有任何问题,请告诉我。谢谢!

【问题讨论】:

    标签: java arraylist indexing multidimensional-array


    【解决方案1】:

    您不能仅仅因为索引用于访问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;
      }
    }
    

    然后只是传递这个而不是原始对象。

    但是,如果您不需要在逻辑上将它们放在二维数组中,此时您可以只使用包装器而不使用任何二维数组。

    【讨论】: