when I use ArrayList in Java, there are some things that I do not understand. Here is my initialization code:
ArrayList<Integer> list = new ArrayList <Integer> ();
list.add (0);
list.add (1);
sometimes I need to delete an object by its index:
list.remove (0) // delete the object in the first box
but sometimes I want to delete an object by its contents:
list.remove (0) // delete the object HAS Which value of 0
this code is very ambiguous. To clarify what I want to do it in code, I specify the type like this:
list.remove ((Object) 0) // delete the object which has a value of 0
If I do not AC, the only way to know which methods are called is to put the mouse pointer on the method to see: java.util.ArrayList.remove boolean (Object object)
Java But how does it make difference? is there a method pointer? Is there a less ambiguous way to do this?
thank you very much, sorry for my English.
PS: I should say that I finally used SparseIntArray but I am curiously
If it is just the ambiguity with the remove() method in Integer ArrayList is bothering you, you can extend the ArrayList to implement your own :
public class MyIntArrayList extends ArrayList<Integer> {
boolean removeByObject(Integer intObj) {
return super.remove(intObj);
}
Integer removeByIndex(int index) {
return super.remove(index);
}
}
For staters. List#remove(index) returns the Object removed from the list. List#remove(Object) returns a boolean.
In this special case however. you could do .
ArrayList<Integer> list = new ArrayList <Integer> ();
list.add (0);
list.add (1);
System.out.println(list.remove(new Integer(0)));
Whenever there is an ambiguity in Java (when multiple method signatures could match the types of the parameters at compile time), using casts to choose the right method is your only choice. Of course you could cast and store the parameters into local variables of the correct type before the actual invocation, but this doesn't make it clearer for the reader - casting the parameter directly where it is used is the best option, in my opinion, to make it clear which method is called.
By the way the reason the API is so ambiguous in this case is that at the time the API was made, there was no Auto-Boxing so it was not possible to write ambiguous code like this in the first place. However changing the method to make it unambiguous would have been a breaking change. Since storing Integer in an ArrayList isn't that great of an idea anyway most of the time, they decided to let us live with that slight annoyance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With