如何在int数组中找到元素的索引? [英] How to find the index of an element in an int array?

查看:103
本文介绍了如何在int数组中找到元素的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 int 类型的Java数组中找到某个值的索引?

How can I find an index of a certain value in a Java array of type int?

I尝试在我的未排序数组上使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆