![](/img/trans.png)
[英]Java: How to find index of last element of partially initialized sorted array
[英]How to find the index of an element in an array in Java?
我正在寻找一个给定元素的索引,知道它的内容,在 Java 中。
我尝试了以下示例,但不起作用:
class masi {
public static void main( String[] args ) {
char[] list = {'m', 'e', 'y'};
// should print 1
System.out.println(list[] == "e");
}
}
谁能解释一下这有什么问题以及我需要做些什么来解决它?
在这种情况下,您可以从字符数组创建 e 新字符串,然后对该字符串执行 indeoxOf("e") :
System.out.println(new String(list).indexOf("e"));
但是在其他原始数据类型的情况下,您必须对其进行迭代。
或者,您可以使用 Commons Lang ArrayUtils类:
int[] arr = new int{3, 5, 1, 4, 2};
int indexOfTwo = ArrayUtils.indexOf(arr, 2);
有针对不同数组类型的indexOf()
方法的重载变体。
这甚至不是有效的语法。 而你正试图与一个字符串进行比较。 对于数组,您必须自己遍历数组:
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);
}
}
如果您使用的是集合,例如ArrayList<Character>
您还可以使用indexOf()
方法:
ArrayList<Character> list = new ArrayList<Character>();
list.add('m');
list.add('e');
list.add('y');
System.out.println(list.indexOf('e'));
还有Arrays
类可以缩短上面的代码:
List list = Arrays.asList(new Character[] { 'm', 'e', 'y' });
System.out.println(list.indexOf('e'));
从 Java 8 开始,原始数组arr
和搜索val
值的通用解决方案是:
public static int indexOf(char[] arr, char val) {
return IntStream.range(0, arr.length).filter(i -> arr[i] == val).findFirst().orElse(-1);
}
此代码使用IntStream.range
在数组的索引上创建一个流, 过滤索引以仅保留该索引处的数组元素等于搜索值的那些,最后保持第一个与findFirst
匹配。 findFirst
返回一个OptionalInt
,因为可能没有找到匹配的索引。 所以我们调用orElse(-1)
要么返回找到的值,要么返回-1
如果没有找到。
可以为int[]
、 long[]
等添加重载。方法的主体将保持不变。
对于对象数组,比如String[]
,我们可以使用相同的想法并使用equals
方法进行过滤步骤,或者Objects.equals
来考虑两个null
元素相等, 而不是==
。
但我们可以用更简单的方式做到这一点:
public static <T> int indexOf(T[] arr, T val) {
return Arrays.asList(arr).indexOf(val);
}
这为使用所述输入阵列的列表包装Arrays.asList
,并搜索与该元素的索引indexOf
。
此解决方案不适用于原始数组, 如下所示:像int[]
这样的原始数组不是Object[]
而是Object
; 因此,在其上调用asList
会创建单个元素的列表,该列表是给定的数组,而不是数组元素的列表。
我相信
唯一最
明智的方法是手动遍历数组。
for (int i = 0; i < list.length; i++) {
if (list[i] == 'e') {
System.out.println(i);
break;
}
}
您的代码的问题在于,当您这样做时
list[] == "e"
你问的是数组对象(不是内容)是否等于字符串“e”,这显然不是这种情况。
您需要遍历内容以进行所需的检查:
for(String element : list) {
if (element.equals("e")) {
// do something here
}
}
最简单的解决方案:
将数组转换为列表,您可以获得元素的位置。
List<String> abcd = Arrays.asList(yourArray);
int i = abcd.indexOf("abcd");
其他解决方案,您可以迭代数组:
int position = 0;
for (String obj : yourArray) {
if (obj.equals("abcd") {
return position;
}
position += 1;
}
//OR
for (int i = 0; i < yourArray.length; i++) {
if (obj.equals("abcd") {
return i;
}
}
现在它确实打印了 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;
}
}
请记住
"e"
是一个字符串对象字面量(它代表一个字符串对象)
尽管
'e'
是字符文字(表示字符原始数据类型)
即使当
list[]
将一个字符元素与一个字符串元素进行比较将是有效的 Java(它不是)无论如何都会返回 false。
只需使用该 indexOf 字符串函数,您就可以在任何字母表(或字符数组)中找到任何字符
非常大量的编辑。 我想要么你想要这个:
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'];
}
}
(请注意,如果您想使用 1-26 而不是 0-25,则可能需要调整 init 方法)
或者你想要这个:
int getLetterPossitionInAlphabet(char c) {
return c - 'a' + 1
}
第二个是如果你总是想要 a=1,z=26。 第一个会让你输入一个像 "qwerty" 这样的字符串并赋值 q=0, w=1, e=2, r=3 ...
这种方式应该有效,将“char”更改为“Character”:
public static void main(String[] args){
Character[] list = {'m', 'e', 'y'};
System.out.println(Arrays.asList(list).indexOf('e')); // print "1"
}
这是另一个示例以及indexOf
是如何工作的。
public int indexOf(Object target) {
for (int i = 0; i < array.length; i++) {
if (equals(target, array[i])) {
return i;
}
}
return -1;
}
如果元素的初始顺序不是很重要,你可以只对数组进行排序,然后 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') );
}
}
我正在提供正确的方法来做到这一点
/**
* 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;
}
这样您最多可以使用“N”个字母。
char[] a={ 'a', 'b', 'c', 'd', 'e' };
int indexOf=0;
for(int i=0;i<a.length;i++){
if(a[i] != 'b'){
indexOf++;
}else{
System.out.println("index of given: "+indexOf);
}}
int i = 0;
int count = 1;
while ('e'!= list[i] ) {
i++;
count++;
}
System.out.println(count);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.