问题
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.
these are the values that list stores.
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;
}
}
This is the output I get:
index of 5 =
index of 100 =
回答1:
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;
}
}
I didn't know what ListNode was for, because it was actually not needed.
I would like to encourage you to see how ArrayList<> implementation in openjdk looks like: ArrayList.java#ArrayList.lastIndexOf in OpenJDK
回答2:
This code shouldn't have 2 return statements. Also, you are making a node equal the entire list; when it should equal the head of the list.
Was this code given to you to correct? I ask because it does not appear to have been developed piece-wise; rather it looks written from the top down.
回答3:
Use this I guess:
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;
}
来源:https://stackoverflow.com/questions/23330664/i-dont-understand-how-lastindexof-method-works-in-java