0

I'm trying to find the index of an object placed in an array. The array has been populated like this

for(i = 0 ; i<n ;i++){
    for(j=0; j<n ;j++){
        squares[i][j]= new Square(i,j)
        }

So the array is basically full of Square objects with no name. I want to make a method that returns the index of a square object, like:

getObject(Square s){
{

I've seen other answers calling for the use of

Arrays.asList(array)

And stuff like that, but they all try to return the index for an int or a String.

How should i go about returning the index for any object?

3 Answers 3

1

As long as the comparison operator (equals() method) of your Square is suitable for you, then any of these method would work :

  • Converting to ArrayList and unsing indexOf and get
  • Using java.util.Arrays.binarySearch
  • Do a foreach loop and search manually
  • etc.

You only need a valid comparison operator, if the default Object.equals()(comparison of object instances) is suitable for your need, then you don't have much to do :

Point getObject(Square s){
{
    for(int i = 0; i<n; i++){
        for(int j = 0; j<n; j++){
            if( squares[i][j].equals(s) ) {
                return Point(i, j);
            }
        }
    }
    return null;
}

Note that if your array is large, it's not the fastest way to do it.

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

Comments

0

if you can use equals method (assuming n is defined also, or you can use length) :

public int[] getObject(Square s){

int[] returnIndex = new int[2];

for(int i = 0 ; i<this.n ;i++){
    for(int j=0; j<this.n ;j++){ 

        if(s.equals(this.squares[i][j])) {
               returnIndex[0] = i;
               returnIndex[1] = j;
               return returnIndex;
            }

       }
    }
    return null;
}

Comments

0

i have solved like this

private ArrayList<Square> squareList= new ArrayList<Square>(9);

  for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                mSquare[i][j] = new Square(i, j);
                squareList.add(mSquare[i][j]);
            }
        }

    public int index(int r, int c) {
        return squareList.indexOf(Square(r, c));
    }

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.