在java中查找集合中的弱引用对象

发布于 2024-07-24 10:23:35 字数 583 浏览 1 评论 0原文

关于 Java 的 WeakReference 和 Collections 的几个问题:

  1. 是否有一个库可以使用 Wea​​kReference 透明地实现 Java 的各种数据集接口(例如 Collection、List、Set、Queue 等)? 就像 WeakHashMap 是针对 HashMap 接口一样?

  2. 或者是简单地创建普通集合然后使用某种技巧与compareTo或比较器或其他东西来使搜索集合正确工作的常见解决方案?

我基本上希望这样:

public interface WeakCollection<E> extends Collection<E> {}

但接口的约定是对 E 的引用存储较弱。 显然,当该对象消失时, get(int index) 返回 null 等问题,我没有问题,但我想要 contains(E e) 函数和其他函数像这样的项目才能正常工作。

我只是想避免“不是在这里发明的”陷阱,并确保如果我自己实现它,它是最简单的解决方案。

A couple of questions regarding Java's WeakReference and Collections:

  1. Is there a library out there that implements Java's various data-set interfaces (eg Collection, List, Set, Queue etc) with WeakReference transparently? Like WeakHashMap is for the HashMap interface?

  2. Or is the common solution to simply create normal Collections and then use some sort of trick with compareTo or a Comparator or something to make searching the collection work correctly?

I basically would like this:

public interface WeakCollection<E> extends Collection<E> {}

But the contract for the interface is that the references to E are stored weakly. Obviously I do not have a problem with get(int index) returning null when that object has gone away etc, but I would like the contains(E e) function and other items like it to work properly.

I'm just trying to avoid the "not invented here" trap and ensuring that if I do implement this myself that its the simplest solution possible.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼泪都笑了 2024-07-31 10:23:35

JBoss 有一个 WeakSet。 在 Java 6 中, 你也可以这样做

Set<T> s = Collections.newSetFromMap(new WeakHashMap<T, Boolean>());

我还发现了一个 WeakArrayList如果有帮助的话,那就是 LGPL。

JBoss has a WeakSet. In Java 6, you can also do

Set<T> s = Collections.newSetFromMap(new WeakHashMap<T, Boolean>());

Also I found a WeakArrayList that's LGPL if that helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文