`

Use overloading judiciously

UP 
阅读更多

Effective Java 2rd ITEM 41: USE OVERLOADING JUDICIOUSLY

审慎地使用重载,看下面的例子,猜一下结果会是什么:

 

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class SetList {
	public static void main(String[] args) {
		Set<Integer> set = new TreeSet<Integer>();
		List<Integer> list = new ArrayList<Integer>();
		for (int i = -3; i < 3; i++) {
			set.add(i);
			list.add(i);
		}
		for (int i = 0; i < 3; i++) {
			set.remove(i);
			list.remove(i);
		}
		System.out.println(set + " " + list);
	}
}

 

 

 

 

安全、保守的策略是不要设计两个具有相同参数的重载函数,除非参数类型差别很大,Two types are radically different if it is clearly impossible to cast an instance of either type to the other.

上例的结果是[-3, -2, -1] [-2, 0, 2],原因解释如下:

 

Here’s what’s happening: The call to set.remove(i) selects the overloading
remove(E), where E is the element type of the set (Integer), and autoboxes i
from int to Integer. This is the behavior you’d expect, so the program ends up
removing the positive values from the set. The call to list.remove(i), on the
other hand, selects the overloading remove(int i), which removes the element at
the specified position from a list. If you start with the list [-3, -2, -1, 0, 1, 2]
and remove the zeroth element, then the first, and then the second, you’re left with
[-2, 0, 2], and the mystery is solved. To fix the problem, cast list.remove’s
argument to Integer, forcing the correct overloading to be selected. Alternatively,
you could invoke Integer.valueOf on i and pass the result to list.remove.
Either way, the program prints [-3, -2, -1] [-3, -2, -1], as expected:

 

for (int i = 0; i < 3; i++) {
    set.remove(i);
    list.remove((Integer) i); // or remove(Integer.valueOf(i))
}
 

主要是说的Set的remove选择了remove(E)重载版本(只有这一个吧),而List选择了remove(i)

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics