可比的和泛型的 [英] comparable and generics

查看:97
本文介绍了可比的和泛型的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,
我在B处尝试使用泛型来实现它,以便在实例化时可以使用任何键,值对数据类型.但是,我陷在下面的比较中.
我只想比较返回-1,0或1的值并执行常规的二进制搜索树操作


Hello,
I have B where I am trying to implement it using generics so that any key,value pair data type can be used when instantiated. However, I get stuck on the compare below.
I just simply want to compare values return -1,0 or 1 and do normal binary search tree operations


public class RedBlackBST<TKey, TValue> 
     {
          private Node root;
          public int redCount = 0;
          public int totalNodes = 0;
          private static Boolean RED = true;
          private static Boolean BLACK = false;

          private class Node
          {
.
.
.
.
.
.

private Node put(Node h, TKey key, TValue val)
          {
               if (h == null) // Do standard insert, with red link to parent.
               {
                    return new Node(key, val, 1, RED);
               }
               int cmp = key.compareTo(h.key); //This is where I get stuck
               if (cmp < 0)
               {
                    h.left = put(h.left, key, val);
               }
               else if (cmp > 0)
               {
                    h.right = put(h.right, key, val);
               }
               else
               {
                    h.val = val;
               }
               if (isRed(h.right) && !isRed(h.left))
               {
                    h = rotateLeft(h);

               }
               if (isRed(h.left) && isRed(h.left.left))
               {
                    h = rotateRight(h);

               }
               if (isRed(h.left) && isRed(h.right))
               {
                    flipColors(h);

               }
               h.N = size(h.left) + size(h.right) + 1;
               return h;
          }

推荐答案

您必须告诉TKey是IComparable.

You must tell that the TKey is IComparable.

public class RedBlackBST<TKey, TValue> where TKey: IComparable
{
   ...
} 


目前尚不清楚确切的错误是什么,但看看卡在哪里,关键的对象看起来就不具有可比性.检查msdn以获取更多信息:
http://msdn.microsoft.com/en-us/library/system.icomparable. compareto.aspx [ ^ ]

祝你好运!
It isn''t very clear what the exact error is, but looking at where you get stuck it looks like the key ojects aren''t comparable. Check msdn for more info:
http://msdn.microsoft.com/en-us/library/system.icomparable.compareto.aspx[^]

Good luck!


这篇关于可比的和泛型的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆