我想在java中创建一个二叉搜索树。键将是字符串,我将按字母顺序比较字符串。我想把我的“键”变成char数组,这样我就可以轻松编写一个方法来检查字母顺序。不幸的是,除了equals()
,getClass()
,wait()
,toString()
,HashCode()
,Notify()
之外,我无法使用任何字符串方法。我想使用substring
方法和toCharArray()
方法,如stringName.substring()或stringName.toCharArray(),但我无法联系到它们。代码如下:
public class BST<V,String> {
public class Node <V,String> {
private Node right=null;
private Node left=null;
private String key;
private V value=null;
public Node(V value, String key){
this.key=key;
this.value=value;
}
}
Node root=null;
Node temp=null;
public void add(V value, String key){
if(isEmpty()){
root.value=value;
root.key=key;
}
else{
temp=root;
while(true){
if(key > temp.key){
if(temp.right==null){
Node node= new Node(value,key);
temp.right=node;
}
temp=temp.right;
}
else if(key < temp.key)
if(temp.left==null){
Node node= new Node(value,key);
temp.left=node;
}
temp=temp.left;
}
}
}
public boolean isEmpty(){
if(root.value==null){
return true;
}
else
return false;
}
}
答案 0 :(得分:2)
宣布:
public class BST<V,String>
...你已经在你的班级上宣布了两个通用参数;一个名为V
,另一个名为String
。
你可能要做的事情是省略密钥的泛型类型,因为你知道它仍然是String
:
public class BST<V>
答案 1 :(得分:1)
你的错误在于public class BST<V,String>
的声明中。
您有String
作为通用参数,并且隐藏了实际的String类。因此,你写的String
实际上是什么。
解决方案是放弃通用参数String
,从而产生public class BST<V>
。事情会有效,因为String
将不再被隐藏。
请注意,eclipse会对此发出警告:
类型参数String隐藏类型String