如何在Java中找到数组中元素的索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1522108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find the index of an element in an array in Java?
提问by
I am looking to find the index of a given element, knowing its contents, in Java.
我正在寻找一个给定元素的索引,知道它的内容,在 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?
谁能解释一下这有什么问题以及我需要做些什么来解决它?
采纳答案by Bart Kiers
In this case, you could create e new String from your array of chars and then do an indeoxOf("e") on that String:
在这种情况下,您可以从字符数组创建 e 新字符串,然后对该字符串执行 indeoxOf("e") :
System.out.println(new String(list).indexOf("e"));
But in other cases of primitive data types, you'll have to iterate over it.
但是在其他原始数据类型的情况下,您必须对其进行迭代。
回答by Matt Solnit
I believe the onlysanest way to do this is to manually iterate through the array.
我相信唯一最明智的方法是手动遍历数组。
for (int i = 0; i < list.length; i++) {
if (list[i] == 'e') {
System.out.println(i);
break;
}
}
回答by Joey
That's not even valid syntax. Andyou're trying to compare to a string. For arrays you would have to walk the array yourself:
这甚至不是有效的语法。而你正试图与一个字符串进行比较。对于数组,您必须自己遍历数组:
public class T {
public static void main( String args[] ) {
char[] list = {'m', 'e', 'y'};
int index = -1;
for (int i = 0; (i < list.length) && (index == -1); i++) {
if (list[i] == 'e') {
index = i;
}
}
System.out.println(index);
}
}
If you are using a collection, such as ArrayList<Character>
you can also use the indexOf()
method:
如果你正在使用一个集合,比如ArrayList<Character>
你也可以使用这个indexOf()
方法:
ArrayList<Character> list = new ArrayList<Character>();
list.add('m');
list.add('e');
list.add('y');
System.out.println(list.indexOf('e'));
There is also the Arrays
class which shortens above code:
还有一个Arrays
类可以缩短上面的代码:
List list = Arrays.asList(new Character[] { 'm', 'e', 'y' });
System.out.println(list.indexOf('e'));
回答by Peter
The problem with your code is that when you do
您的代码的问题在于,当您这样做时
list[] == "e"
you're asking if the array object (not the contents) is equal to the string "e", which is clearly not the case.
你问的是数组对象(不是内容)是否等于字符串“e”,这显然不是这种情况。
You'll want to iterate over the contents in order to do the check you want:
您需要遍历内容以进行所需的检查:
for(String element : list) {
if (element.equals("e")) {
// do something here
}
}
回答by Bill K
Very Heavily Edited. I think either you want this:
非常大量的编辑。我想要么你想要这个:
class CharStorage {
/** set offset to 1 if you want b=1, o=2, y=3 instead of b=0... */
private final int offset=0;
private int array[]=new int[26];
/** Call this with up to 26 characters to initialize the array. For
* instance, if you pass "boy" it will init to b=0,o=1,y=2.
*/
void init(String s) {
for(int i=0;i<s.length;i++)
store(s.charAt(i)-'a' + offset,i);
}
void store(char ch, int value) {
if(ch < 'a' || ch > 'z') throw new IllegalArgumentException();
array[ch-'a']=value;
}
int get(char ch) {
if(ch < 'a' || ch > 'z') throw new IllegalArgumentException();
return array[ch-'a'];
}
}
(Note that you may have to adjust the init method if you want to use 1-26 instead of 0-25)
(请注意,如果您想使用 1-26 而不是 0-25,则可能需要调整 init 方法)
or you want this:
或者你想要这个:
int getLetterPossitionInAlphabet(char c) {
return c - 'a' + 1
}
The second is if you always want a=1, z=26. The first will let you put in a string like "qwerty" and assign q=0, w=1, e=2, r=3...
第二个是如果你总是想要 a=1,z=26。第一个会让你输入一个像 "qwerty" 这样的字符串并赋值 q=0, w=1, e=2, r=3 ...
回答by Powerlord
If the initial order of elements isn't really important, you could just sort the array, then binarySearch it:
如果元素的初始顺序不是很重要,你可以只对数组进行排序,然后 binarySearch 它:
import java.util.Arrays;
class masi {
public static void main( String[] args ) {
char[] list = {'m', 'e', 'y'};
Arrays.sort(list);
// should print 0, as e is now sorted to the beginning
// returns negative number if the result isn't found
System.out.println( Arrays.binarySearch(list, 'e') );
}
}
回答by OscarRyz
Now it does print 1
现在它确实打印了 1
class Masi {
public static void main( String [] args ) {
char [] list = { 'm', 'e', 'y' };
// Prints 1
System.out.println( indexOf( 'e', list ) );
}
private static int indexOf( char c , char [] arr ) {
for( int i = 0 ; i < arr.length ; i++ ) {
if( arr[i] == c ) {
return i;
}
}
return -1;
}
}
Bear in mind that
请记住
"e"
is an string object literal ( which represents an string object that is )
是一个字符串对象字面量(它代表一个字符串对象)
While
尽管
'e'
'e'
Is a character literal ( which represents a character primitive datatype )
是字符文字(表示字符原始数据类型)
Even when
即使当
list[]
Would be valid Java ( which is not ) comparing the a character element with a string element would return false anyway.
将一个字符元素与一个字符串元素进行比较将是有效的 Java(它不是)无论如何都会返回 false。
Just use that indexOf string function and you could find any character within any alphabet ( or array of characters )
只需使用该 indexOf 字符串函数,您就可以找到任何字母表(或字符数组)中的任何字符
回答by Manmohan Soni
I am providing the proper method to do this one
我正在提供正确的方法来做到这一点
/**
* Method to get the index of the given item from the list
* @param stringArray
* @param name
* @return index of the item if item exists else return -1
*/
public static int getIndexOfItemInArray(String[] stringArray, String name) {
if (stringArray != null && stringArray.length > 0) {
ArrayList<String> list = new ArrayList<String>(Arrays.asList(stringArray));
int index = list.indexOf(name);
list.clear();
return index;
}
return -1;
}
回答by Max77
Alternatively, you can use Commons Lang ArrayUtilsclass:
或者,您可以使用 Commons Lang ArrayUtils类:
int[] arr = new int{3, 5, 1, 4, 2};
int indexOfTwo = ArrayUtils.indexOf(arr, 2);
There are overloaded variants of indexOf()
method for different array types.
indexOf()
对于不同的数组类型,有重载的方法变体。
回答by Kehe CAI
This way should work, change "char" to "Character":
这种方式应该有效,将“char”更改为“Character”:
public static void main(String[] args){
Character[] list = {'m', 'e', 'y'};
System.out.println(Arrays.asList(list).indexOf('e')); // print "1"
}