Java:在列表中找到字符串的索引 [英] Java: Find the index of a String in a list
问题描述
我有一个列表:
public static List<String> codes = new LinkedList<String>(Arrays.asList(
"Zero",
"One"
)); //Etc..
我希望能够在键入String
时找到其位置编号.例如,如果我键入One
,我希望程序打印出1
.目前,我只能使用codes.get();
I want to be able to find the number of a String
's position when I type it. For instance, if I type One
, I want the program to print out 1
. Currently, I can only do the reverse by using codes.get();
更正:我希望程序打印出String在列表中的位置. Zero
的位置为0
,如果我执行codes.get(0);
,则得到Zero
.但是,我该如何做相反的事情?
Correction: I want the program to print out the position of the String in the list. Zero
has the position 0
, if I do codes.get(0);
I get Zero
. But how do I do the reverse?
有没有一种方法可以顺利地做到这一点?预先感谢.
Is there a way to smoothly do this? Thanks in advance.
推荐答案
The reverse of codes.get()
is indexOf(Object obj)
method
返回指定元素在此列表中首次出现的索引;如果此列表不包含该元素,则返回-1.
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
codes.indexOf("One");
这篇关于Java:在列表中找到字符串的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!