在Java中查找数组中的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3384203/
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-13 22:48:25  来源:igfitidea点击:

Finding an element in an array in Java

javaarrays

提问by Casebash

Does Java have a built-function to allow me to linearly search for an element in an array or do I have to just use a for loop?

Java 是否有内置函数来允许我线性搜索数组中的元素,或者我是否必须只使用 for 循环?

采纳答案by Douglas

There is a containsmethod for lists, so you should be able to do:

有一种contains列表方法,因此您应该能够执行以下操作:

Arrays.asList(yourArray).contains(yourObject);

Warning: this might not do what you (or I) expect, see Tom's comment below.

警告:这可能不符合您(或我)的预期,请参阅下面的汤姆评论。

回答by duffymo

Use a for loop. There's nothing built into array. Or switch to a java.util Collection class.

使用 for 循环。数组中没有任何内容。或者切换到 java.util Collection 类。

回答by hvgotcodes

You might want to consider using a Collectionimplementation instead of a flat array.

您可能需要考虑使用Collection实现而不是平面数组。

The Collectioninterface defines a contains(Object o)method, which returns true/false.

Collection接口定义了一个contains(Object o)方法,该方法返回true/ false

ArrayListimplementation defines an indexOf(Object o), which gives an index, but that method is not on all collection implementations.

ArrayList实现定义了一个indexOf(Object o),它给出了一个索引,但该方法并不适用于所有集合实现。

Both these methods require proper implementations of the equals()method, and you probably want a properly implemented hashCode()method just in case you are using a hash based Collection(e.g. HashSet).

这两种方法都需要正确实现该equals()方法,并且您可能需要正确实现的hashCode()方法,以防万一您使用基于散列的Collection(例如HashSet)。

回答by krock

You can use one of the many Arrays.binarySearch()methods. Keep in mind that the array must be sorted first.

您可以使用多种Arrays.binarySearch()方法之一。请记住,必须先对数组进行排序。

回答by Trenton

With Java 8, you can do this:

使用 Java 8,您可以这样做:

int[] haystack = {1, 2, 3};
int needle = 3;

boolean found = Arrays.stream(haystack).anyMatch(x -> x == needle);

You'd need to do

你需要做

boolean found = Arrays.stream(haystack).anyMatch(x -> needle.equals(x));

if you're working with objects.

如果您正在处理对象。