Ashot
Ashot

Reputation: 77

Strong and weak references in one collection

Suppose the situation in which we must have list of WeakReference and "Strong Reference".But there are not StrongReference class in Java.My solution is

Keep list of objects

 List<? extends Object> list =new ArrayList();

and any time when we get element from list, check:

if(list.get(i) instanceof WeakReference){
     MyClass myObject =  ((MyClass)((WeakReference) list.get(i)).get());
     if(myObject != null){
       myObject.doSomething();
     }
  }else{
     MyClass myObject =  ((MyClass)list.get(i));
     myObject.doSomething();
  } 

Is there better solution to keep strong and weak references together in one collection?.

Upvotes: 0

Views: 258

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533820

I would write it something like this

Object o = list.get(i);
if (o instanceof WeakReference) o = ((WeakReference) o).get();
if (o instanceof MyClass) ((MyClass) o).doSomething();

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234857

I'd be tempted to abstract the concept of "strong or weak reference":

public interface DualRef<T> {
    T get();
}

Then implement two subclasses, one for weak references:

public class WeakDualRef<T> implements DualRef<T> {
    private final WeakReference<T> mRef;
    public WeakDualRef(T object) {
        mRef = new WeakReference<T>(object);
    }
    public WeakDualRef(WeakReference<T> ref) {
        mRef = ref;
    }
    T get() {
        return mRef.get();
    }
}

and another for strong references:

public class StrongDualRef<T> implements DualRef<T> {
    private final T mRef;
    public StrongDualRef(T object) {
        mRef = object;
    }
    public T get() {
        return mRef;
    }
}

Then you can implement your code as:

List<DualRef<MyObject>> list = new ArrayList<DualRef<MyObject>>();

// add mixed instances of WeakDualRef<MyObject> or StringDualRef<MyObject> . . .

MyClass myObject = list.get(i).get();
myObject.doSomething();

All this has the advantage of preserving type safety through proper use of generics.

Upvotes: 3

Aubin
Aubin

Reputation: 14873

Mixing types is not a good conception.

List< WeakReference > weakRefs  = new ArrayList<>();
List< MyClass >       myClasses = new ArrayList<>();

With two loops to do two different thing.

Why mixing two different kind of object, they don't share any behavior.

Upvotes: 0

Related Questions