一个很奇怪的泛型问题。 财富值20

2016-10-27 11:25发布

在编写红黑树的操作时,使用了泛型进行编程。但是在对根节点进行赋值时,却碰到了很奇怪的问题。

下面是定义的红黑树的对象

public class RBTree<T extends Comparable<T>> {      private RBNode<T> mRoot;      public static final boolean RED = true;      public static final boolean BLACK = false;      public RBNode<T> getmRoot() {         return mRoot;     }      public void setmRoot(RBNode<T> mRoot) {         this.mRoot = mRoot;     } }

下面是定义的红黑树中节点对象

public class RBNode<T extends Comparable<T>> {     private RBNode<T> left;     private RBNode<T> right;     private RBNode<T> parent;     private boolean color;     private T key;      public RBNode(RBNode<T> left, RBNode<T> right, RBNode<T> parent, boolean color, T key) {         this.left = left;         this.right = right;         this.parent = parent;         this.color = color;         this.key = key;     }      public RBNode<T> getLeft() {         return left;     }      public void setLeft(RBNode<T> left) {         this.left = left;     }      public RBNode<T> getRight() {         return right;     }      public void setRight(RBNode<T> right) {         this.right = right;     }      public RBNode<T> getParent() {         return parent;     }      public void setParent(RBNode<T> parent) {         this.parent = parent;     }      public boolean isColor() {         return color;     }      public void setColor(boolean color) {         this.color = color;     }      public T getKey() {         return key;     }      public void setKey(T key) {         this.key = key;     } }

在操作类中对红黑树中某个节点进行左旋的过程中报错

public class RBTreeOperation<T extends Comparable<T>> {      private RBTree<T> rbTree;      public RBTreeOperation(RBTree<T> rbTree) {         this.rbTree = rbTree;     }      public <T extends Comparable<T>> void leftRoatate(RBNode<T> x){         RBNode<T> y = x.getRight();         x.setRight(y.getLeft());         if (y.getLeft() != null){             y.getLeft().setParent(x);         }          y.setParent(x.getParent());          if (x.getParent() == null){             ***rbTree.setmRoot(y);***         }else {             if (x.getParent().getLeft() == x){                 x.getParent().setLeft(x);             }else {                 x.getParent().setRight(x);             }         }         y.setLeft(x);         x.setParent(y);     } }

在rbTree.setmRoot(y)中报错,y的类型不匹配。

付费偷看设置
发送
2条回答

public void leftRoatate(RBNode<T> x)

去掉方法中声明的范型,类里已经对T声明过了,再声明1次就变成另外一个范型参数

一周热门 更多>