Java - 检查项目是否在数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9712826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:33:53  来源:igfitidea点击:

Java - Check if item is in array

javaarrays

提问by DannyF247

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

可能的重复:
在 Java 中,如何测试数组是否包含某个值?

I have an array setup as follows:

我有一个数组设置如下:

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

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

如何查看材质是否在此数组中?

采纳答案by óscar López

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

回答by moodywoody

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.

如果您想要一种简单的方法来检查元素是否属于集合的一部分,您可能应该考虑使用不同的数据结构,例如 Set(并使用 contains())。使用 Array 您只能迭代元素并比较每个元素。

回答by Tom

How about looking for it using the Arraysclass?

如何使用Arrays类查找它?

See Arrays#binarySearch

参见数组#binarySearch

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

或者按照某人的建议,将您的数组转换为List并使用contains()方法。请记住,您可能必须覆盖 Material#equals 方法。