这是通用二进制搜索树的代码。我还没有实现搜索功能,因为我已经在行上有错误:1,2和3,我已在代码中指出。错误说:
运营商<未定义参数类型T,T。
所以,我猜编译器不知道如何比较这些类型或类似的东西。现在,我做了一些研究,我发现它与Comperable和compareTo方法有关,但作为一个java新手自己,我还没有设法修复代码。关于如何修复它的任何想法?
import java.util.*;
import java.io.*;
public class Tree<T>
{ private Node<T> root = null;
public boolean insert(T element)
{ if (isEmpty())
{ root = new Node<T>(element);
return true; }// empty tree, Node could be inserted, return true
Node<T> current = root; // start at root
Node<T> parent; // the current Node's parent
do
{parent = current;
if (element < current.element) // 1
current = current.left; // go to left
else if (element > current.element) //2
current = current.right; // go to right
else
return false; } // duplicates are NOT allowed, element could not be inserted -> return false
while (current != null);
Node<T> node = new Node<T>(element);
if (element < current.element) // 3
parent.left = node;
else
parent.right = node;
return true; } // node successfully inserted
public boolean isEmpty() { return root == null; }
private static class Node<T> // static member class
{ Node<T> left = null;
Node<T> right = null;
final T element;
Node(T element) { this.element = element; } }
}
答案 0 :(得分:1)
<
,<=
,>=
和>
等比较运算符仅为数字类型定义。
要比较其他类型,您需要:
使用实现Comparable
的类型,例如String
。您可以通过向类型变量添加约束来执行此操作:
public class Tree<T extends Comparable<T>>
这意味着您可以调用compareTo
方法:
if (element.compareTo(current.element) < 0) {
传入Comparator
,可以比较该类型的实例:
public boolean insert(T element, Comparator<? super T> comparator)
然后用它来比较元素:
if (comparator.compare(element, current.element)) {