These days in reading "Effective Java" this book, in the 41st--careful use of heavy load this chapter found a usually not attention to the problem.
First look at the example:
public static void Main (string[] args) {
set<integer> Set = new treeset<integer> ();
list<integer> list = new arraylist<integer> ();
for (int i=0;i<10;i++)
{
set.add (i);
List.add (i);
}
SYSTEM.OUT.PRINTLN (set + " " + list);
for (int i =0;i<5;i++)
{
set.remove (i);
List.remove (i);
}
SYSTEM.OUT.PRINTLN (set + " " + list);
}
The desired output result is:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9] [5, 6, 7, 8, 9]
But the real output is:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9] [1, 3, 5, 7, 9]
This is why. Mainly because of:
Set.remove (i) invokes the overloaded method remove (e), where E is a set (integer) type, automatically boxing the I to Integer when used, and this is what we expect.
List.remove (i) called overloaded method Remove (int i) removes an element from the location specified in the list.
list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], first remove the No. 0 element to get [1, 2, 3, 4, 5, 6, 7, 8, 9]
Then remove the 1th element to get [1, 3, 4, 5, 6, 7, 8, 9], and so on, and finally get [1, 3, 5, 7, 9]
The problem is found, then talk about how to solve the problem, in fact, it is very simple, just to convert the parameters of List.remove to Integer is good, first look at the code:
public static void Main (string[] args) {
set<integer> Set = new treeset<integer> ();
list<integer> list = new arraylist<integer> ();
for (int i=0;i<10;i++)
{
set.add (i);
List.add (i);
}
SYSTEM.OUT.PRINTLN (set + " " + list);
for (int i =0;i<5;i++)
{
set.remove (i);
List.remove ((Integer) i);
}
SYSTEM.OUT.PRINTLN (set + " " + list);
}
The results of the output are:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9] [5, 6, 7, 8, 9]
Finally, the understanding of the overload: a sentence,
the ability to use overloaded methods does not mean that you should use overloaded。 In general, overloaded methods should be avoided as much as possible for multiple methods with the same parameters.
Avoid situations where the same set of parameters can be passed to different overloaded methods only through type transitions.