如何在Java中找到数组中元素的索引? [英] How to find the index of an element in an array in Java?
本文介绍了如何在Java中找到数组中元素的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望在 Java 中找到给定元素的索引,知道其内容.
I am looking to find the index of a given element, knowing its contents, in Java.
我尝试了以下示例,但不起作用:
I tried the following example, which does not work:
class masi {
public static void main( String[] args ) {
char[] list = {'m', 'e', 'y'};
// should print 1
System.out.println(list[] == "e");
}
}
谁能解释一下这有什么问题以及我需要做些什么来解决它?
Can anyone please explain what is wrong with this and what I need to do to fix it?
推荐答案
在这种情况下,您可以从字符数组中创建一个新的 String,然后对该 String 执行 indeoxOf("e") :
In this case, you could create e new String from your array of chars and then do an indeoxOf("e") on that String:
System.out.println(new String(list).indexOf("e"));
但在其他原始数据类型的情况下,您必须对其进行迭代.
But in other cases of primitive data types, you'll have to iterate over it.
这篇关于如何在Java中找到数组中元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文