4

Possible Duplicate:
In Java, how can I test if an Array contains a certain value?

I have an array setup as follows:

Material[] blockedlevel1 = {
            Material.mymaterialone, Material.mymaterialtwo  
        };

How do I see if a Material is in this array?

1
  • Look for it, I'd think. There's that "do loop" thingie. Commented Mar 15, 2012 at 1:34

3 Answers 3

8

How about looking for it in the array?

for (Material m : blockedlevel1) {
    if (m.equals(searchedMaterial)) { // assuming that equals() was overriden
        // found it! do something with it
        break;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

How would I set what "m" is so that I can compare it to the array? I need to check Material block = event.getBlock().getType(); (that is my material).
In the above loop, m gets bound to each of the array's elements in turn; you don't need to set it, the for loop does it for you. What you need to take care of, is to provide a searchedMaterial against which you can compare (it'd be block in your example), to implement an equals() method in the Material class, and to do something inside the if, once you find the material.
3

If you want an easy way to check if an element is part of a collection you should probably consider a different data-structure like Set (and use contains()). With Array you can only iterate over the elements and compare each one.

Comments

1

How about looking for it using the Arrays class?

See Arrays#binarySearch

Or as someone suggested, turn your array into a List and use the contains() method. Remember that you may have to override the Material#equals method.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.