我不明白lastIndexOf方法在Java中的工作方式 [英] I don't understand how lastIndexOf method works in java
问题描述
我必须编写一个名为LastIndexOf的方法,该方法接受一个整数值作为参数,并返回该值最后一次出现的列表中的索引;如果找不到该值,则返回-1.这是我的代码,但不返回任何内容.在我看来,它总是会返回-1,但我在输出中看不到它,因为它不打印方法返回的内容.
I have to write a method called LastIndexOf that accepts an integer value as a parameter and that returns the index in the list of the last occurrence of the value, or -1 if the value is not found. This is the code I have but it doesn't return anything. To me it looks that it always is going to return -1 but I can't see it on the output because it doesn't print what the method returns.
这些是列表存储的值.
列表-> [2、5、7、24、5、9、13、2]
list -> [2, 5, 7, 24, 5, 9, 13, 2]
public class LastIndexOf {
public static void main(String[] args) {
System.out.println("index of 5 = " + list.lastIndexOf(5)); // should to return index of 5= 4
System.out.println("index of 100 = " + list.lastIndexOf(100)); // should return index of 100 = -1
}
public static int lastIndexOf (int element) {
int index = 0;
ListNode current = list;
while (current != null) {
if (current.data == element) {
return index;
}
index ++;
current = current.next;
}
return -1;
}
}
这是我得到的输出:
index of 5 =
index of 100 =
推荐答案
此代码段返回正确的值.
This snippet returns correct values.
public class Test
{
public static java.util.List<Integer> list = Arrays.asList(2, 5, 7, 24, 5, 9, 13, 2);
public static void main(String[] args)
{
System.out.println("index of 5 = " + list.lastIndexOf(5));
System.out.println("index of 100 = " + list.lastIndexOf(100));
System.out.println(lastIndexOf(5));
System.out.println(lastIndexOf(100));
}
public static int lastIndexOf (int element) {
int index = 0;
int found = -1;
List<Integer> current = list;
while (index < current.size()) {
if (current.get(index) == element) {
found = index;
}
index ++;
}
return found;
}
}
我不知道ListNode是干什么的,因为实际上并不需要它.
I didn't know what ListNode was for, because it was actually not needed.
我想鼓励您了解openjdk中ArrayList <>的实现方式:
I would like to encourage you to see how ArrayList<> implementation in openjdk looks like: ArrayList.java#ArrayList.lastIndexOf in OpenJDK
这篇关于我不明白lastIndexOf方法在Java中的工作方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!