[英]I don't understand how lastIndexOf method works in java
我必須編寫一個名為LastIndexOf的方法,該方法接受整數值作為參數,並返回該值最后一次出現的列表中的索引;如果找不到該值,則返回-1。 這是我的代碼,但不返回任何內容。 對我來說,它看起來總是會返回-1,但是我在輸出中看不到它,因為它不打印方法返回的內容。
這些是列表存儲的值。
列表-> [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 =
此代碼不應包含2個return語句。 同樣,您要使節點等於整個列表。 什么時候應該等於列表的開頭。
是否已將此代碼提供給您進行更正? 我問,因為它似乎不是分段開發的; 而是看起來是從上到下。
此代碼段返回正確的值。
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是干什么的,因為實際上並不需要它。
我想鼓勵您看看openjdk中ArrayList <>的實現如何: OpenJDK中的ArrayList.java#ArrayList.lastIndexOf
我猜用這個:
public int lastIndexOf (int value) {
int index = -1;
int size = size();
int count = 0;
ListNode current = front;
for (int i = 0; i < size; i++) {
int indexValue = current.data;
if (value == current.data) {index = count;}
count++;
current = current.next;
}
return index;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.