Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Collections Linked List | removing an object 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.
So 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()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading