1

尽管花费了大量时间在谷歌上搜索我的困境的答案并重新阅读了我的 Java 教科书中关于泛型的章节,但我似乎无法用以下代码解决问题:

public class RedBlackTree<I extends Comparable>
{
    private int count = 0;
    private RedBlackNode root;

    private RedBlackNode current;
    private RedBlackNode[] stack;

    /**
     * Inner class used for representing the nodes of the red-black balanced binary search tree object.
     */
    private class RedBlackNode implements Comparable
    {
        private I id;
        private boolean is_btree;
        private RedBlackNode[] links;

        /**
         * Constructor for objects of the RedBlackNode class.
         * 
         * @param id The ID of the node.
         */
        private RedBlackNode(I id)
        {
            if (id == null)
            {
                throw new NullPointerException("ID cannot be null.");
            }

            this.id = id;
            this.is_btree = true;
        }

        /**
         * Function for comparing the RedBlackNode object to another object.
         * 
         * @param obj The object to be compared.
         * @return If invocant > passed, returns 1; if invocant < passed, returns -1; if invocant = passed, returns 0.
         */
        private int compareTo(Object obj)
        {
            if (obj instanceof RedBlackTree.RedBlackNode)
            {
                RedBlackNode node = (RedBlackNode)obj;

                int result = id.compareTo(node.id);

                return result > 0 ? 1 : result < 0 ? -1 : 0;
            }
            else
            {
                throw new ClassCastException("Expected a RedBlackNode object.");
            }
        }
    }
}

特别是,我收到一个弹出窗口,其中包含以下消息:

Warnings from last compilation

C:\Users\...\RedBlackTree.java uses unchecked or unsafe operations.
Recompile with -Xlint:unchecked for details.

几乎所有 I here 或 Comparable there 的组合仍然会导致这样的弹出窗口。我正在使用 BlueJ 环境进行编程,这使得无法合并相关的编译器参数以查看任何细节。

据我到目前为止的研究可以看出,这与内部类使用 I 泛型类型有关,因此 RedBlackNode 内部类中的“RedBlackNode 实现 Comparable”和 compareTo 方法需要与之抗衡不知何故的事实。

我知道这个问题已经在 stackoverflow 和其他地方被问过并且回答了很多次,但我似乎无法将从这些实例中学到的东西应用到我的案例中。我对泛型很陌生,所以我能在这里得到的任何帮助都将不胜感激!

4

3 回答 3

2

Comparable接受一个 Type 参数。编译器抱怨是因为您没有提供它。

于 2013-03-21T10:55:31.740 回答
2

警告是因为您使用的是原始类型Comparable而不是给它一个类型参数。您所要做的就是将类定义更改为

public class RedBlackTree<I extends Comparable<I>>

private class RedBlackNode implements Comparable<RedBlackNode>

并相应地调整compareTo()方法(这实际上会大大简化它,因为您不再需要类型检查和强制转换)。

于 2013-03-21T11:01:48.437 回答
2

进行以下更改

public class RedBlackTree<I extends Comparable<I>>

private class RedBlackNode implements Comparable<RedBlackNode>

    @Override
    public int compareTo(RedBlackNode node)
            int result = id.compareTo(node.id);
            return result > 0 ? 1 : result < 0 ? -1 : 0;

在 compareTo 中删除类型检查。注意公众,因此始终使用@Override.

于 2013-03-21T11:08:21.563 回答