3

I'm studying Java generics and I was wondering what are the differences due to the use of the wildcard <?> in these two codes:

First

public class Tree<T> {

    private final T node;
    private final Set<Tree<?>> children;

    public Tree(T node, Set<Tree<?>> children) {
        this.node = node;
        this.children = children;
    }

    public static void main(String[] args) {
        Set<Tree<?>> children = new HashSet<>();
        children.add(new Tree<Integer>(new Integer(0), new HashSet<>()));
        children.add(new Tree<String>("asdf", new HashSet<>()));
        Tree<Integer> ti = new Tree<Integer>(new Integer(1), children);
    }
}

Second

public class Tree<T> {

    private final T node;
    private final Set<Tree> children;

    public Tree(T node, Set<Tree> children) {
        this.node = node;
        this.children = children;
    }

    public static void main(String[] args) {
        Set<Tree> children = new HashSet<>();
        children.add(new Tree<Integer>(new Integer(0), new HashSet<>()));
        children.add(new Tree<String>("asdf", new HashSet<>()));
        Tree<Integer> ti = new Tree<Integer>(new Integer(1), children);
    }
}

I wrote a simple main that uses the class, but I'm interested in the differences resulting from different uses of this class (I didn't see any difference with this main).


EDIT: don't know if it's clear from the example, but I don't necessarily want nodes of tree of the same type.

  • `Set` is not to nice since it is using the raw type `Tree`, ignoring the fact that `Tree` is a generic class and should be used with `<>` as in `Tree` or as here, `Tree>`. – Ole V.V. Dec 28 '16 at 14:19
  • 1
    Check this: http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it – beeb Dec 28 '16 at 14:20
  • I read about the raw types, but why I'm not receiving any warning from the compiler? –  Dec 28 '16 at 14:23
  • Re the dupetarget: In particular, [this answer](http://stackoverflow.com/a/2770692/157247) has an entire section called *"How's a raw type different from using > as a type parameter?"*. – T.J. Crowder Dec 28 '16 at 14:30

0 Answers0