简体   繁体   中英

Get Index of 2D Array in an ArrayList

I have an ArrayList filled with objects in a 2D Array. I want to get the indexes of the Object in the 2D Array at the index of the ArrayList. For example:

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]);

What I want to do is:

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

Does anyone know how I can get the indexes of the 2D array at a specific position? (The indexes are random). Let me know if you have any questions. Thanks!

You can't directly retrieve the index just because the index is used to access elements in map but they are not contained in the object. The object itself has no clue of being inside an array.

A better approach would be to store the index inside the object itself:

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;
}

You can even have a wrapper class which works as a generic holder:

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;
  }
}

and then just pass this around instead that the original object.

But, if you don't need to have them logically in a 2D array, at this point you can just use the wrapper without any 2D array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM