some random dude
some random dude

Reputation: 467

Get index of objects in an array

I am trying to find the index of each object in my array.

   public class MonsterTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Monster [] ma = new Monster[3];
        ma[0] = new Vampire();
        ma[1] = new Dragon();
        ma[2] = new Monster();
        for(int x = 0; x < 3; x++) {
            System.out.println(ma[x].getClass());
            System.out.println(java.util.Arrays.asList(ma[x]).indexOf(x));
            ma[x].frighten(x);

        }

    }

}

Am I using the java.util.Arrays.asList(ARRAY).indexOf(element) method here correct? (Well I am obviously not because the output is incorrect.

Upvotes: 1

Views: 1157

Answers (3)

fabian
fabian

Reputation: 82531

Let's take a look at what your code does:

java.util.Arrays.asList(ma[x])

creates a List containing exactly 1 element: ma[x].

Perhaps you are trying to do this instead, to create a list of all Monsters in array ma:

java.util.Arrays.asList(ma)

/*...*/.indexOf(x)

This tries to find a Integer in the list. (auto boxing of your loop variable). This obviously returns -1 since there are no Integers (only Monsters) in the list.

To get a result != -1 you have to pass a Monster as argument to indexOf, e.g. something like this:

/*...*/.indexOf(ma[x])

(which will return x btw., if you use my both modifications above and none of your monsters are equal (using equals) and equals is reflexive, which is the case if you don't override it)

Upvotes: 0

AlexUseche
AlexUseche

Reputation: 150

The issue is here:

System.out.println(java.util.Arrays.asList(ma[x]).indexOf(x));

You are specifying an index where you shouldn't in the parameter of the asList method. Instead try this:

System.out.println(java.util.Arrays.asList(ma).indexOf(x));

Upvotes: 0

Ivaylo Toskov
Ivaylo Toskov

Reputation: 4041

You already have it - it's x. You don't need to use such a specific functions to get something you already have.

public class MonsterTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Monster [] ma = new Monster[3];
        ma[0] = new Vampire();
        ma[1] = new Dragon();
        ma[2] = new Monster();
        for(int x = 0; x < 3; x++) {
            System.out.println(ma[x].getClass());
            System.out.println(x);
            ma[x].frighten(x);

        }

    }

}

Upvotes: 1

Related Questions