Java-Collection集合- 关于optional operation

Collection类中的一些方法上有(optional operation)标识
例如:
add()方法

boolean java.util.Collection.add(E e)

Ensures that this collection contains the specified element (optional operation). Returns true if this collection changed as aresult of the call. (Returns false if this collection doesnot permit duplicates and already contains the specified element.)

Collections that support this operation may place limitations on whatelements may be added to this collection. In particular, somecollections will refuse to add null elements, and others willimpose restrictions on the type of elements that may be added.Collection classes should clearly specify in their documentation anyrestrictions on what elements may be added.

If a collection refuses to add a particular element for any reasonother than that it already contains the element, it must throwan exception (rather than returning false). This preservesthe invariant that a…

第一次看到不知道表达什么意思。
因为会想到,接口中的方法不都是要求必须实现的嘛。
查了下资料:
https://stackoverflow.com/questions/10572643/optional-methods-in-java-interface

得出结论
个人理解:当初Java的Collection接口设计者在设计的时候,因为要Collection的类有很多实现。
但是这些实现,并不是每一个都用得上这些方法。所以标注了optional operation
问:既然不实现,为什么要继承Collection接口呢?
答案:因为如果要想完全地实现,每一个类继承”Collection“接口时,都用得上所有的方法。那么,需要设计很多接口。权衡之下,选择了optional operation标注。

具体例子:
Collections中的内部类UnmodifiableList。就是设计来作为:一个不可改变的List。它不需要add方法,但是接口还是继承了Collection。所以,它的add()方法的具体实现为,抛出一个标识没有实现该方法的异常

    static class UnmodifiableList<E> extends UnmodifiableCollection<E>
                                  implements List<E> {
        private static final long serialVersionUID = -283967356065247728L;

        final List<? extends E> list;

        UnmodifiableList(List<? extends E> list) {
            super(list);
            this.list = list;
        }
        .....
//。所以,它的add()方法的具体实现为,如下
        public boolean add(E e) {
            throw new UnsupportedOperationException();
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值