尽管花费了大量时间在谷歌上搜索我的困境的答案并重新阅读了我的 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 和其他地方被问过并且回答了很多次,但我似乎无法将从这些实例中学到的东西应用到我的案例中。我对泛型很陌生,所以我能在这里得到的任何帮助都将不胜感激!