0

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?.

Ashot
  • 77
  • 5

3 Answers3

3

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.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

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.

Aubin
  • 14,617
  • 9
  • 61
  • 84
0

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();
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130