如何在int数组中找到元素的索引? [英] How to find the index of an element in an int array?
本文介绍了如何在int数组中找到元素的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 int
类型的 Java 数组中找到某个值的索引?
How can I find an index of a certain value in a Java array of type int
?
我尝试在我的未排序数组上使用 Arrays.binarySearch
,它只是有时给出正确的答案.
I tried using Arrays.binarySearch
on my unsorted array, it only sometimes gives the correct answer.
推荐答案
Integer[] array = {1,2,3,4,5,6};
Arrays.asList(array).indexOf(4);
请注意,此解决方案是线程安全的,因为它创建了一个 List 类型的新对象.
Note that this solution is threadsafe because it creates a new object of type List.
此外,您也不想在循环或类似的情况下调用它,因为您每次都会创建一个新对象
Also you don't want to invoke this in a loop or something like that since you would be creating a new object every time
这篇关于如何在int数组中找到元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文