Search code examples
javalinked-listlastindexof

I don't understand how lastIndexOf method works in java


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 = 

Solution

  • 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