1

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.

1
  • What does Arrays.asList(..) do? What does indexOf(..) do? (Go see.) Commented May 31, 2014 at 0:09

3 Answers 3

1

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

        }

    }

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

Comments

0

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

2 Comments

This results in the same output.
Yes, cause you are correctly giving the list as an argument ma , but look for the index of object of type Integer and not of type Monster. If you want to rely on this approach, use System.out.println(java.util.Arrays.asList(ma).indexOf(ma[x]));
0

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)

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.