0

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!

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.