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 :
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));