我有一个类似集合的接口(interface),其中包含 Collection
接口(interface)的大部分方法,但是存在与 add
和 contains
相关的问题> 我关心的方法只是从 Collection
继承。
Collection
中类型为 T
的元素实现了一个copy
方法和一个 setter,有时需要按以下方式实现:
- 在通过提供的 setter 插入元素之前更改元素
- 创建元素的副本,通过提供的 setter 更改一个或两个元素,然后才插入它们
可以通过考虑采用字符串参数的集合来形象化这一点,但是如果添加了特定字符串 foo
,则截断版本 fo
或 fo
加上另一个字符串 bar
被添加。
// Examples of the add() method internals
collection.add("foo"); // internally add("fo");
collection.add("foo"); // internally add("fo"); add("bar");
问题是,有时会插入多个元素,这本身对于 add
中的方法契约是没问题的,但在插入之前更改元素有点脏。如果使用 copy
方法并插入元素,它将不再包含
原始元素。
问题:扩展 Collection
是否正确,或者重新定义大多数集合方法是更好的选择吗?
最佳答案
如果它的行为如您描述的那样,您的接口(interface)不应该扩展 Collection
,因为它确实违反了 Collection
的 add
的约定,这说:
Ensures that this collection contains the specified element
和
If a collection refuses to add a particular element for any reason other than that it already contains the element, it must throw an exception (rather than returning false). This preserves the invariant that a collection always contains the specified element after this call returns.
如果 collection.add("foo");
实际上添加了“fo”,那么契约就被破坏了。
如果您的界面扩展了 Collection
,您界面的用户可以将您的界面实例分配给 Collection
变量,并期望它的行为如 集合
接口(interface)。
关于java - 类集合接口(interface)继承自 Collection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56627354/