3

I have a class with a ReferenceQueue of WeakReferences.

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();
[...]

But when I try to compile this I get an "incompatible types" error:

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();
                                                               ^

I do not understand this, because I have defined the reference queue as a queue of weak references of V and so I expect a weak reference of V as a result of remove().

Is this wrong? How can I fix this?

I tried also Reference<V> as a return value of remove() but that does not help. I tried the cast the result but that turns the error only into a warning.

ceving
  • 21,900
  • 13
  • 104
  • 178

1 Answers1

4

You should be using ReferenceQueue<V>, not ReferenceQueue<WeakReference<V>>. You'll need to explicitly cast the references you pull out of the queue to WeakReference<V>.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • Is there no way to get the type right without generating the "unchecked cast" warning? – ceving Jun 07 '13 at 18:28
  • 1
    Ok. I added a `@SuppressWarnings`. My [example](http://stackoverflow.com/questions/1802809/javas-weakhashmap-and-caching-why-is-it-referencing-the-keys-not-the-values/16991188#16991188) seems to work. – ceving Jun 07 '13 at 19:06