Java 数组中的元素位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4234827/
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
Element position in array
提问by AVi
I have an array:
我有一个数组:
char[] modifiers = {'A', 'M', 'D'};
and a variable:
和一个变量:
char a = 'D'
How to get position of variable value in array?
如何获取数组中变量值的位置?
Thanks
谢谢
回答by icyrock.com
Try:
尝试:
int pos = -1;
for(int i = 0; i < modifiers.length; i++) {
if(modifiers[i] == a) {
pos = i;
break;
}
}
This will get the firstoccurrence of the value in variable pos
, if there are multiple ones, or -1 if not found.
这将获得变量中第一次出现的值pos
,如果有多个,或者 -1 如果没有找到。
回答by khachik
Iterate through the array and compare its elements to the variable, return the index, if equals. Return -1 if not found. You might want to consider using any implementation of java.util.List
.
遍历数组并将其元素与变量进行比较,如果相等,则返回索引。如果未找到,则返回 -1。您可能需要考虑使用java.util.List
.
回答by khachik
Something along the lines may do the trick:
一些事情可能会奏效:
Collections.indexOfSubList(Arrays.asList(array), Arrays.asList('D'))
Trying to avoid a manual loop :p
试图避免手动循环:p
回答by President James K. Polk
You could do it yourself easily enough, you can use the sort() and binarySearch() methods of the java.util.Arrays class, or you can convert the char [] to a String and use the String.indexOf() method.
您可以很容易地自己完成,您可以使用 java.util.Arrays 类的 sort() 和 binarySearch() 方法,或者您可以将 char [] 转换为 String 并使用 String.indexOf() 方法。
回答by st0le
This is the shortest way I know. I had this as a comment but now writing it as an answer. Cheers!
这是我知道的最短路径。我将此作为评论,但现在将其写为答案。干杯!
Character[] array = {'A','B','D'};
Arrays.asList(array).indexOf('D');
Character[] 数组 = {'A','B','D'};
Arrays.asList(array).indexOf('D');
回答by Manimaran Samuthirapandi
This is very simple and tested code for your reference
这是非常简单且经过测试的代码供您参考
String[] arrayValue = {"test","test1","test2"};
int position = Arrays.asList(arrayValue).indexOf("test");
position: 0th Position