Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with Observer Pattern and generics in Java

I have made a generic Observer interface and an Observable class, but can't compile my class due to some generics problem. I don't know precisely why what I'm trying to do is forbidden. The code follows:

public class Observable<U> {

    private List<Observer<Observable<U>, U>> _observers = 
            new ArrayList<Observer<Observable<U>, U>>();

    public void addObserver(Observer<? extends Observable<U>, U> obs) {
        if (obs == null) {
            throw new IllegalArgumentException();
        }
        if (_observers.contains(obs)) {
           return;
        }
        _observers.add(obs); // This line does not compile
    }

    public void notifyObservers(U data) {
        for (Observer<? extends Observable<U>, U> obs : _observers) {
            // After correction of the list declaration, this line will not compile
            obs.update(this, data); 
        }        
    }
}

interface Observer<T, U> {
    public void update(T entity, U arg);
}
like image 201
Thiago Chaves Avatar asked Jan 23 '23 10:01

Thiago Chaves


1 Answers

Change your _observers definition to this:

private List<Observer<? extends Observable<U>, U>> _observers = 
        new ArrayList<Observer<? extends Observable<U>, U>>();

If you want to allow sublclasses you need to specify this in the declaration, not just in the place you're using it

like image 122
tddmonkey Avatar answered Feb 04 '23 18:02

tddmonkey