java - 类集合接口(interface)继承自 Collection

标签 java collections interface

我有一个类似集合的接口(interface),其中包含 Collection 接口(interface)的大部分方法,但是存在与 addcontains 相关的问题> 我关心的方法只是从 Collection 继承。

Collection 中类型为 T 的元素实现了一个copy 方法和一个 setter,有时需要按以下方式实现:

  • 在通过提供的 setter 插入元素之前更改元素
  • 创建元素的副本,通过提供的 setter 更改一个或两个元素,然后才插入它们

可以通过考虑采用字符串参数的集合来形象化这一点,但是如果添加了特定字符串 foo,则截断版本 fofo 加上另一个字符串 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,因为它确实违反了 Collectionadd 的约定,这说:

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/

相关文章:

java - 使用流畅的接口(interface)重构长方法

java - 使用 Tomcat 在 IIS 中配置 PHP

wpf - 如何将 List 作为 ItemSource 绑定(bind)到 XAML 中的 ListView?

c++ - 我的框架 : Collection of unknown subclasses (hotspot)

java - 提高HashSet的速度

java - 尝试查找 .bmp 文件的高度和宽度在处理中得到不一致的结果

java - hibernate 到 MSSQL 服务器连接被拒绝 : connect

iphone - 如何启动 iPhone 应用程序使其不使用任何 nib 文件?

java接口(interface)方法从子类中删除

c# - 接口(interface)和只有一个抽象方法的抽象类有什么区别?