immutablelist java_java – ImmutableList不扩展List?

为什么ImmutableList不扩展List?

ImmutableCollection不扩展java.util.Collection(并且ImmutableList不扩展java.util.List),因为Collection具有add()和remove()等变异方法.如果不可变集合具有这些方法,则它们总是必须抛出UnsupportedOperationException.对于不可变集合的用户,在自动完成选择中将add()和remove()看作可调用方法会很奇怪.

为什么Javadoc强加一个所有ImmutableList实现也实现List的契约?

归结为平等. ImmutableList应该等于List,假设两个列表具有相同顺序的相同内容. List.equals() imposes a Javadoc contract:

Returns true if and only if the specified object is also a list, both

lists have the same size, and all corresponding pairs of elements in

the two lists are equal.

“指定的对象也是一个列表是什么意思?”我们可以在AbstractList.equals()中看到它表示instanceof List.

public boolean equals(Object o) {

if (o == this)

return true;

if (!(o instanceof List))

return false;

...

}

因此,所有ImmutableList实现也必须实现List for equals()以对称方式工作.不可变集合工厂已经隐藏了实现细节,例如具有单个元素的不可变列表由ImmutableSingletonList实现.它还最终隐藏了List接口.

互操作

这种设计的一个好处是可以将ImmutableList转换为List,这对于与现有API互操作很重要.

// Library method - cannot refactor the parameter type

public void printAll(List> list)

{

for (Object each : list)

{

System.out.println(each);

}

}

ImmutableList immutableList = Lists.immutable.with(1, 2, 3);

List castList = immutableList.castToList();

printAll(castList);

// also works

printAll((List>) immutableList);

// throws UnsupportedOperationException

castList.add(4);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值