无法决定的Java集合

huangapple go评论53阅读模式
英文:

Unable to decide Java collection

问题

我的用例类似于需要维护一组唯一项目。我可能需要经常在集合中的索引处添加或删除项目(目前我将索引作为项目成员,但我可以进行修改),在执行此操作时我需要更新项目的索引。

我无法确定哪种Java集合最适合我的需求。HashSet和SortedSet都保证了唯一性,但不确定如何处理索引部分。

英文:

My usecase is like in which I need to maintain a collection of unique items. I may need to frequently add or remove items from the collection at an index(which I have as member of the item currently, but I am open to modification), and while doing that I need to update index of items.

I am not able to decide which Java collection would suit my needs best. HashSet and SortedSet both guarantee uniqueness, but not sure how index part can be taken care of.

答案1

得分: 2

根据问题和评论,您对集合有以下基本要求:

  1. 集合中的元素必须是唯一的。
  2. 集合必须按照用户指定的顺序维护元素。
  3. 集合元素必须具有表示元素当前位置的唯一索引。
  4. 在插入和删除元素时,索引必须进行调整。

Java SE 中没有单一的集合类型可以同时满足 1 和 2,3 或 4。

唯一支持并能够维护任意顺序的 Java SE 集合类型是 List,因此您需要从那里开始。可以像这样实现:

public class MyList<E> extends ArrayList<E> {
    ...

    @Override
    public void add(int pos, E e) {
        if (this.contains(e)) {
            throw new SomeException("already in collection");
        }
        this.add(pos, e);
    }
}

请注意,HashMap<Integer, E> 是一种可能的替代方案,但在添加和删除元素时调整索引是复杂的。(性能特性的比较并不直观,但很可能在您的用例中并不重要。)

英文:

According to the question + comments, you have the following fundamental requirements for the collection:

  1. The elements in the collection must be unique.
  2. The collection must maintain the elements in an order specified by the user.
  3. The collection elements must have unique indexes representing the element's current position.
  4. The indexes must adjust as elements are inserted and deleted.

There is no (single) Java SE collection type that does 1 and 2, 3 or 4.

The only Java SE collection type that supports and can maintain an arbitrary ordering is List, so you need to start with that. Something like this for instance:

public class MyList&lt;E&gt; extends ArrayList&lt;E&gt; {
    ...

    @Override
    public void add(int pos, &lt;E&gt; e) {
        if (this.contains(e)) {
            throw new SomeException(&quot;already in collection&quot;);
        }
        this.add(pos, e);
    }
}

Note that HashMap&lt;Integer, E&gt; is a possible alternative, but adjusting the indexes as elements are added and removed is complicated. (Comparing the performance characteristics is not straightforward, but the chances are that it won't matter in your use-case.)

huangapple
  • 本文由 发表于 2020年8月22日 10:01:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/63531898.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定