3

I have this generic class

public class BinTree<T> {

    T value;

    List<BinTree<? extends T>> branch = new ArrayList<BinTree<? extends T>>();

    public BinTree(T v){ value  = v;}

    public void addBranch(BinTree<? extends T> tree){
        if(branch.size() == 2){
            System.out.println("You can only have two childs");
        }else{
            branch.add(tree);
        }
    }

    public BinTree<? extends T> getBranch(int n){ return branch.get(n);}


}

And its implementation here

public static void main(String[] args){
        BinTree<Number> firstBinTree = new BinTree<Number>(0);
        firstBinTree.addBranch(new BinTree<Integer>(5));
        firstBinTree.addBranch(new BinTree<Double>(6.5));

        Number o = firstBinTree.getBranch(0).value;
        firstBinTree.getBranch(0).addBranch(new BinTree<Integer>(6));

    }   

But this line

firstBinTree.getBranch(0).addBranch(new BinTree<Integer>(6));

Is not allowing me to add another BinTree of Type integer. why is that? I declared in my addBranch method that it can add any type as long that is ia subclass of Type(in this case number) it would be added in the list but how come I can't ? isn't Integer a sub class of Number?

user962206
  • 15,637
  • 61
  • 177
  • 270

2 Answers2

2

It will not know if the

<? extends T> 

in getBranch and addBranch are the same i think. So to it will be

<? extends ? extends T>
Markus Mikkolainen
  • 3,397
  • 18
  • 21
1

It is because generics are not covariant.

In your example getBranch(0) can return BinTree<? extends Number> (for example BinTree<Integer> or BinTree<Double>) but compiler can't be sure about precise generic type that will be used. So from safety reasons it won't allow to use BinTree<Integer> in addBranch in case getBranch(0) will return something different then BinTree<Integer> like BinTree<Double>.

Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269