Removing the “first” object from a Set

前端 未结 6 1884
北恋
北恋 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 06:58

    Quick and dirty one-line solution: mySet.remove(mySet.toArray(new Foo[mySet.size()])[0]) ;)

    However, I'd still go for the iterator solution, since this would be more readable and should also be faster.

    Edit: I'd go for Mike Samuel's solution. :)

提交回复
热议问题