This is not a duplicate! It's true that the literal question has been asked before, but neither the question had same intention (focus on int and Integer and deprecation) nor the answers answered what I was looking for.
I looked a lot through StackOverflow. I seen the same questions and answers over and over again, but they don't address the real problem.
There is Java. Java has ArrayList
. ArrayList
has the method remove()
.
The JDK9 Documentation says it can take the index as a parameter or the object itself that you want to be removed.
The following code does not work though.
import java.util.*;
public class Tea {
public static void main (String[] args) {
ArrayList<Integer> myList = new ArrayList<Integer>();
myList.add(69);
myList.remove( ( (int) 69 ) );
System.out.println(myList);
}
}
It compiles, but it does not run and so it gives the following error message:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 69 out-of-bounds for length 1
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:372)
at java.base/java.util.ArrayList.remove(ArrayList.java:517)
at Tea.main(Tea.java:10)
The JVM is obviously taking the argument as the index and not the object. Here's the suggested solution found on the other websites:
myList.remove(new Integer(69));
It doesn't even compile into bytecode:
Note: Tea.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Compiling with:
$javac Tea.java -Xlint:deprecation
Gives us:
warning: [deprecation] Integer(int) in Integer has been deprecated
myList.remove(new Integer(69));
I looked in the deprecated list on the documentation. Couldn't find it. Looked the method's documentation to have it explained to me. No explanation.
All I want to do is use the parameter as an object and not the index and get my return as a boolean (documentation says so) if it was in the ArrayList
and has been removed.
Is there a way to do this? Or is it deprecated and my Ctrl +F search on the deprecated methods not enough?