javalinked-listremove-method

Removing an object from a LinkedList vs element using .remove() method


LinkedList arr = new LinkedList<>();
arr.add(2);
arr.add("Anam");
arr.add(1);
System.out.println(arr);
arr.remove(2);
arr.remove("Anam");
System.out.println(arr);

This is a LinkedList of 3 elements of mixed data types (int and String). I want to use .remove() method to remove using an object name not index. How do I remove element 2 (at index 1) without using the index, but using the object (element) name via .remove(object) method?

I am using IntelliJ and after many trials, I cannot perform this.

P.S: Every time I try to use .remove(object), it automatically infers an index value. How to use .remove to remove an integer value, by using Integer object as .remove() method argument? I don't want to use index in .remove().


Solution

  • Lists in java have the methods remove(Object o) and remove(int index). When you use .remove(2), the 2 is recognized as a primitive int. To use the Object Integer, you need to pass the parameter like this:

        arr.remove(Integer.valueOf(2));
    

    or like this:

        arr.remove((Object) 2);
    

    This casts the primitive int into the object Integer, which then calls remove(Object o) instead of remove(int index).