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

Remove element from Vector(any collection) in JAVA

How to remove element from an Integer type Vector in JAVA by using remove(Object o)?
This is a short snippet of what I did. I’m new to Java.


    Vector<Integer> v = new Vector<>();

    v.add(1);
    v.add(2);
    v.add(3);

    Object remInd = v.remove(0);    // Index based, THIS WORKS!!!
        
    boolean remElem = v.remove("3");    // HOW TO MAKE THIS WORK? IT ALWAYS RETURNS 'false'


        // I tried this, it works.

    Object num = 3;
        
    boolean remElem = v.remove(num);    // returns 'true'


>Solution :

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

In one you are trying to remove a String but the collection contains integers:

v.remove("3");

An option could be if you want to convert a String to the value:

v.remove(Integer.parseInt("3"));

But this is also an excellent example of why Autoboxing can cause problems. What should happen here, remove 2nd element at index 1 or remove 1st element with value 1?

v.remove(1);

Doing this makes it very clear that Integer type a the value should be removed:

v.remove(Integer.valueOf(1));
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