1

I want to make a binary tree keep node as heap so that I try to make a generic in generic but I got some problem about it.

1-)I could not figure out two layer generic is it possible in Java.

2-)I adding tree as number but when I try to return node I dont now assign what and can I reach it methods if it can be return .

Binary Search Tree Heap Tree

public class BSTHeapTree <E extends Comparable<? extends Comparable<?>>>{
        
    BinarySearchTree<E<T>> root;    //error
    public BSTHeapTree() {
        root = new BinarySearchTree<>(); // error
    }
    
    int add(E _data) {
         = root.getRoot();      //Assign what
        return 0;
    }

}

Binary Search Tree

public class BinarySearchTree<E extends Comparable<E>>{
    
    private Node<E> head;
    
    public BinarySearchTree() {
        head = null;
    }
    public Node<E> getRoot() {
        return head;
    }

    private static class Node<E extends Comparable<E>>{
        
        E data;
        Node<E> lBranch;
        Node<E> rBranch;
    }
}

Heap

public class Heap<E extends Comparable<E>> implements Comparable<Heap<E>>{

   private E[] heapData;
}
Turing85
  • 18,217
  • 7
  • 33
  • 58
mbulucay
  • 37
  • 5
  • In the example given, `E` could be of any type (for example `String`). But not every type does have a generic paraemter, thus `E` is not possible. In general, we only care about `E`, not its inner generic parameter (see, for example, [Java 8's implementation of `LinkedList`](https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/LinkedList.java). – Turing85 Apr 24 '21 at 10:19
  • So I cannot reach the generic of generic node of Tree when I want to reach am I right – mbulucay Apr 24 '21 at 10:21
  • You can... if you use bounded types. For example: `public void , T>, foo(E e) { ... }` works. Applying [PECS](https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super), we can then furhter restrict `T`, depending on how `E` is used within the method, e.g. `public void , T>, foo(E e) { ... }` if `E` is used as a producer. – Turing85 Apr 24 '21 at 10:24
  • Here is a small [Ideone demo](https://ideone.com/Njpb8j) showing how to use bounded types. – Turing85 Apr 24 '21 at 10:39
  • Why not use `>` fir `BSTHeapTree`? – dan1st Apr 24 '21 at 11:03

0 Answers0