Removing the “first” object from a Set

前端 未结 6 1871
北恋
北恋 2021-02-05 06:42

Under certain situations, I need to evict the oldest element in a Java Set. The set is implemented using a LinkedHashSet, which makes this simple: just get rid of t

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-05 07:19

    If you really need to do this at several places in your code, just write a static method.

    The other solutions proposed are often slower since they imply calling the Set.remove(Object) method instead of the Iterator.remove() method.

    @Nullable
    public static  T removeFirst(Collection c) {
      Iterator it = c.iterator();
      if (!it.hasNext()) { return null; }
      T removed = it.next();
      it.remove();
      return removed;
    }
    

提交回复
热议问题