Common interface: a list of something specific
I want to define an interface MyList, which is a list of the MyThing interface. Part of the semantics of MyList is that its operations have no meaning for objects that do not implement the MyThing interface.
Is this the correct declaration?
interface MyList<E extends MyThing> extends List<E> { ... }
edit: (part 2) Now I have another interface that returns MyList as one of its methods.
// I'm defining this interface
// it looks like it needs a wildcard or template parameter
interface MyPlace {
MyList getThings();
}
// A sample implementation of this interface
class SpecificPlace<E extends MyThing> implements MyPlace {
MyList<E> getThings();
}
// maybe someone else wants to do the following
// it a class that is specific to a MyNeatThing which is
// a subclass of MyThing
class SuperNeatoPlace<E extends MyNeatThing> implements MyPlace {
MyList<E> getThings();
// problem?
// this E makes the getThings() signature different, doesn't it?
}
source to share
Yes, at least it looks like that EnumSet
.
public abstract class EnumSet<E extends Enum<E>>
extends AbstractSet<E>
Edit in response to part 2:
I'm not sure why the return type getThings()
in the interface doesn't complain about raw types. I suspect that due to type erasure, the warnings in the interfaces would be useless even if they were there (no warning if you change the return type to List
, either).
In the second question, because it MyNeatThing
continues MyThing
, it E
is within its boundaries. That's the point of using bindings extends
in a shared parameter, right?
source to share
For part 1, yes, it looks correct.
From your side 2, I suggest something like the following. The method returns MyList
that you don't know what it is (differently, for different implementations), but you know that it is a subtype of MyThing.
interface MyPlace {
MyList<? extends MyThing> getThings();
}
source to share
Be aware that implementing interfaces like java.util.List correctly is tricky; so ask yourself all these questions:
- Can java.util.List be used "as is", do I need to add / remove functionality?
- Is there something simpler that I could implement, such as Iterable <T>?
- Can I use composition? (against inheritance)
- Can I find the new functionality I want in existing libraries like Google Collections?
- If I need to add / remove functionality, is the added complexity worth it?
However, you could just use java.util.List for your example:
interface MyPlace<T extends MyThing> {
List<T> getThings();
}
class SpecificPlace implements MyPlace<MyThing> {
public List<MyThing> getThings() { return null; }
}
class SuperNeatoPlace implements MyPlace<MyNeatThing> {
public List<MyNeatThing> getThings() { return null; }
}
source to share