Why is this allowable?
abstractclass VertexSetGraph<T>implements Graph<T>
{
...
private Set<Vertex><?extends T>> _verticies;
...
publicboolean addVertex(Vertex<?extends T> vertex)
{
_verticies.add(vertex);
...
}
}
I don't understand why the compiler allows this. Lets say I have:
VertexSetGraph<Animal> graphOfAnimal;
and also though the course of the program _verticies is constructed to be a
Set<Vertex><Dog>>
where Dog extends Animal. I would think the add method would then allow:
graphOfAnimal.addVertex(new Vertex<Cat>);
which makes no sense to me.
I would think that _verticies being a "set of vertex of something extending Animal" would mean that when I called add passing a "vertex of something extending Animal" I can not promise that the two somethings will always be the same type and as such I should not allow compilation. What am I missing?
# 2
I filled in some of the missing pieces. Maybe you can find a tweak that will allow this to compile and still exhibit the problem you describe. If not, I'd say the problem doesn't exist.
import java.util.HashSet;
import java.util.Set;
public class Gen3 {
public static void main(String[] args) throws Exception {
VertexSetGraph<Animal> graph = new VertexSetGraph<Animal>() {};
graph.addVertex(new Vertex<Cat> ());
}
}
interface Graph<T> {}
abstract class VertexSetGraph<T> implements Graph<T> {
private Set<Vertex><? extends T>> _verticies = new HashSet<Dog>(); // INCOMPATIBLE TYPES ERROR AT COMPILE TIME
public boolean addVertex(Vertex<? extends T> vertex){
return _verticies.add(vertex);
}
}
class Vertex<E> {
E data;
}
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
Gen3.java:14: incompatible types
found: java.util.HashSet<Dog>
required: java.util.Set<Vertex><? extends T>>
private Set<Vertex><? extends T>> _verticies = new HashSet<Dog>();
^
1 error
^
jverda at 2007-7-12 20:30:06 >
