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?

Community
  • 1
  • 1
DannyF247
  • 628
  • 4
  • 14
  • 35

3 Answers3

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;
    }
}
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • 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). – DannyF247 Mar 15 '12 at 03:52
  • 2
    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. – Óscar López Mar 15 '12 at 04:00
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.

moodywoody
  • 2,149
  • 1
  • 17
  • 21
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.

Tom
  • 43,810
  • 29
  • 138
  • 169