Use overloading judiciously

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值