LinkedHashSet - 插入顺序和重复 - 保持最新“在顶部” [英] LinkedHashSet - insertion order and duplicates - keep newest "on top"

查看:281
本文介绍了LinkedHashSet - 插入顺序和重复 - 保持最新“在顶部”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个保持插入顺序并具有唯一值的集合。 LinkedHashSet看起来像是要走的路,但是有一个问题 - 当两个项相等时,它会移除最新的一个(这很有意义),这是一个例子:

I need a collection that keeps insertion order and has unique values. LinkedHashSet looks like the way to go, but there's one problem - when two items are equal, it removes the newest one (which makes sense), here's an example:

set.add("one");
set.add("two");
set.add("three");
set.add("two");

将打印 LinkedHashSet


一个两个

但我需要的是:


一个三个两个

one, three, two

这里最好的解决方案是什么?是否有任何可以执行此操作的集合/集合方法,还是应该手动实现?

What would be the best solution here? Is there any collection/collections method that can do this or should I implement it manually?

推荐答案

大多数 Java集合以进行调整。

子类 LinkedHashSet ,覆盖 添加 方法。

Subclass LinkedHashSet, overriding the add method.

class TweakedHashSet<T> extends LinkedHashSet<T> {

    @Override
    public boolean add(T e) {
        // Get rid of old one.
        boolean wasThere = remove(e);
        // Add it.
        super.add(e);
        // Contract is "true if this set did not already contain the specified element"
        return !wasThere;
    }

}

这篇关于LinkedHashSet - 插入顺序和重复 - 保持最新“在顶部”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆