gpt4 book ai didi

java - 为什么 'add' 方法在 AbstractCollection 中不是抽象的?

转载 作者:行者123 更新时间:2023-11-29 05:23:04 25 4
gpt4 key购买 nike

public abstract class AbstractCollection<E> implements Collection<E> {
public boolean add(E e) {
throw new UnsupportedOperationException();
}

add(E e) 方法不是抽象的,而是在扩展抽象类时抛出异常。遵循这种方法有什么好处?如果该方法是抽象的,它将强制覆盖并避免一些困惑。

最佳答案

如果您尝试修改任何不可修改的集合,则抛出 UnsupportedOperationException 是标准行为。例如,它由 Collections.unmodifiable 包装器(目前有八个)返回的类的所有可变方法抛出,例如 Collections.unmodifiableList ,以及不可变的 Collections.emptyList ,以及他们所有的迭代器。

因此,AbstractCollection.add(E) 抛出此异常只是为了通过提供有用的默认行为来更轻松地实现不可修改的集合。您也会在所有这些方法中看到相同的行为:

(此外,许多方法默认抛出异常,这些方法不是故意抛出异常,而是调用有意抛出异常的方法,例如 AbstractList.clear())。

Had the method been made abstract it would have made it mandatory to override and saved some confusion.

也许吧,但是有很多地方需要不可修改的行为,所以有一个默认实现会很方便。它还鼓励不可修改的集合一致地抛出异常;否则有人可能会通过让 add 方法不做任何事情而不是抛出异常来实现它,这会更加困惑。

当您想要一个可修改 集合时,只需查看您扩展的Abstract* 基类的文档,它总是会说明您需要覆盖哪些额外的方法.例如,AbstractCollection says :

To implement an unmodifiable collection, the programmer needs only to extend this class and provide implementations for the iterator and size methods. (The iterator returned by the iterator method must implement hasNext and next.)

To implement a modifiable collection, the programmer must additionally override this class's add method (which otherwise throws an UnsupportedOperationException), and the iterator returned by the iterator method must additionally implement its remove method.

关于java - 为什么 'add' 方法在 AbstractCollection 中不是抽象的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23889410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com