Type argument T is not within bounds of type-variable T(Java Generic) [duplicate]

梦想与她 提交于 2019-12-11 12:02:40

问题


I'm implementing a generic AVL tree but I'm having some compilation error.

My AVL Tee has to deal with Node<T> of type T.

In the example, the type is Event class.I want to compare the node.

But each type of data has to be compared differently, for that, i'm passing the comparison to the data itself to do the comparison.

I tried to make the Node implementing the Comparable Interface and the same thing to Event Class.

My code structure looks as follow:

The Tree Structure:

public class AvlTree<T extends Comparable<T>> {

private Node<T> root;

public AvlTree() {
    root = null;
}
 //other method to insert dellete operation in the tree

    }

The node Structure:

public class Node<T extends Comparable<T>> implements Comparable<T> {
        private T data;
        private Node<T> left;
        private Node<T> right;

        public Node() {
        }
         @Override
        public int compareTo(T t) {
          return this.data.compareTo(t);
        }
     }

The event Class that will be put in a node Object:

public class Event implements Comparable<Event>{
    private Point point;
    public Event() {
    }
    @Override
    public int compareTo(Event t) {
      return 1;
    }
    }

The code that gave me a compilation error is when i'm declaring an AvlTree :

private  AvlTree<Node<Event>> treeOfEvents;

Error:

type argument Node<Event> is not within bounds of type-variable T
where T is a type-variable:
T extends Comparable<T> declared in class AvlTree


回答1:


your Node has to implement Comparable like here:

public class Node<T extends Comparable<T>> implements Comparable<Node<T>> {

as your AvlTree expects something as generic Type which implements Comparable for exactly that type



来源:https://stackoverflow.com/questions/29706044/type-argument-t-is-not-within-bounds-of-type-variable-tjava-generic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!