对于 java 本文提供了三种方法来查找数组中的元素是否包含问题:使用 for 循环遍历数组,检查每个元素是否等于要找到的元素,如果有,则返回 true,无则返回 false。若数组有序,则可使用 arrays.binarysearch() 快速二分搜索的方法,如果找到,返回 true,否则返回 false。使用 stream api 的 arrays.stream(array).anymatch(n -> n == element) 方法,找到就返回 true,否则返回 false。
最直接的方法是使用 for 循环遍历数组,检查每个元素是否等于要找到的元素。如果找到,返回 true,否则返回 false。
public static boolean contains(int[] array, int element) { for (int i = 0; i <h3>方法二:使用 Arrays.binarySearch()</h3><p>若数组有序,可以使用 Arrays.binarySearch() 方法。Arrays.binarySearch() 采用二分搜索算法,可以快速找到元素,时间复杂度为 O(log n)。</p><pre class="brush:php;toolbar:false">public static boolean contains(int[] array, int element) { int index = Arrays.binarySearch(array, element); return index >= 0; }
方法三:使用 Stream API
Java 8 的 Stream API 找到元素提供了一种简单的方法:
public static boolean contains(int[] array, int element) { return Arrays.stream(array).anyMatch(n -> n == element); }
以上就是java数组元素搜索是否包含的详细内容,更多请关注图灵教育的其他相关文章!
