3

我有一个sReferenceQueue的课程。WeakReference

class Example<K,V>
{
    ReferenceQueue<WeakReference<V>> queue = null;
    Thread cleanup = null;
[...]
    Example () {
        queue = new ReferenceQueue<WeakReference<V>>();
        cleanup = new Thread() {
                public void run() {
                    try {
                        for (;;) {
                            WeakReference<V> ref = queue.remove();
[...]

但是当我尝试编译它时,我得到一个“不兼容的类型”错误:

found   : java.lang.ref.Reference<capture#189 of ? extends java.lang.ref.WeakReference<V>>
required: java.lang.ref.WeakReference<V>
                            WeakReference<V> ref = queue.remove();
                                                               ^

我不明白这一点,因为我已将引用队列定义为 V 的弱引用队列,因此我期望 V 的弱引用是remove().

这是错的吗?我怎样才能解决这个问题?

我也尝试Reference<V>将其作为返回值,remove()但这无济于事。我尝试了转换结果,但这只会将错误变成警告。

4

1 回答 1

3

你应该使用ReferenceQueue<V>,而不是ReferenceQueue<WeakReference<V>>。您需要将您从队列中拉出的引用显式转换为WeakReference<V>.

于 2013-06-07T18:18:33.850 回答