I am trying my best to come up with a simple API because generics are not covariant
This is my new problem: I cannot get Set <>, which does what I need. I tried to read various manuals, but they all use a lot of words that I lose.
Consider the following classes
public class Parent {}
public class Child extends Parent {}
interface Store {
public Set<Parent> getParents();
}
At a minimum, I need these operations to work.
Set<Parent> parents = store.getParents();
parents.add(new Parent());
parents.add(new Child());
store.getParents().add(new Child());
for(Parent curEntry : store.getParents()) {
}
Classes that implement the Store should be able to work with Child (this means that they have a Set, which is a child). They need to expose children as parents, albeit for the outside world.
Attempt # 1
interface Store {
public Set<Parent> getParents();
}
class ConcreteStore implements Store {
Set<Child> childs;
public Set<Parent> getParents() {
return (Set<? extends Parent>)childs;
}
}
Attempt # 2
interface Store {
public Set<? extends Parent> getParents();
}
class ConcreteStore implements Store {
Set<Child> childs;
public Set<Child> getParents() {
return childs;
}
}
Store store = new ConcreteStore();
Set<? extends Parent> parents = store.getParents();
parents.add(new Child());
parents.add(new Parent());
for (Parent curEntry : store.getParents()) {
}
, , , Set Concrete . . , .
№ 3
interface Store<T extends Parent> {
public Set<T> getParents();
}
public static class ConcreteStore implements Store<Child> {
Set<Child> childs;
@Override
public Set<Child> getParents() {
return childs;
}
}
Store store = new ConcreteStore();
Set<Parent> parents = store.getParents();
parents.add(new Parent());
parents.add(new Child());
for (Parent curEntry : store.getParents()) {
}
, , Store<Child> store = new DatabaseStore(), - , . , , , .
-
, . , . -