Java 使用相同的类型参数创建类型变量
我必须创建一个二进制搜索树,该树将WordCount对象作为键,并将该单词添加到BST的次数作为值。在我的代码中,我有一个类:Java 使用相同的类型参数创建类型变量,java,Java,我必须创建一个二进制搜索树,该树将WordCount对象作为键,并将该单词添加到BST的次数作为值。在我的代码中,我有一个类: public class WordCountMap<WordCount, V> { private TreeNode root; private WordCount wordItem; /** * This is the node class */ private class TreeNode {
public class WordCountMap<WordCount, V> {
private TreeNode root;
private WordCount wordItem;
/**
* This is the node class
*/
private class TreeNode {
private WordCount item;
private V count;
private TreeNode left;
private TreeNode right;
TreeNode(WordCount item, V count, TreeNode left, TreeNode right) {
this.left = left;
this.right = right;
this.item = item;
}
}
public WordCountMap() {
//Create a new WordCountMap
}
/**
* Adds 1 to the existing count for a word, or adds word to the WordCountMap
* with a count of 1 if it was not already present.
*/
public void incrementCount(String word) {
wordItem = new WordCount(word);
if (root == null) {
root = new TreeNode(wordItem, wordItem.getCount(), null, null);
}
//more code below
}
}
我尝试了@SuppressWarningsrawtypes,但仍然导致了相同的错误 看起来您没有正确使用泛型 假设您用T替换了WordCount的所有实例,无论哪种方式都是相同的程序。在incrementCount中,行wordItem=newTword;但这没有意义,因为您不知道t是否有带字符串参数的构造函数 由于看起来您总是希望键的类型为WordCount,因此您可能希望按如下方式声明该类
public class WordCountMap<V> {}
看起来您没有正确使用泛型 假设您用T替换了WordCount的所有实例,无论哪种方式都是相同的程序。在incrementCount中,行wordItem=newTword;但这没有意义,因为您不知道t是否有带字符串参数的构造函数 由于看起来您总是希望键的类型为WordCount,因此您可能希望按如下方式声明该类
public class WordCountMap<V> {}
我们无法进行新的字数统计。。。当WordCount是一个类型变量时。更多有针对性的回答:你想做什么?为什么要将WordCount作为类型参数?如何实例化新的WordCountMap?我认为需要提供第二个参数。WordCountMap我们无法进行新的WordCount。。。当WordCount是一个类型变量时。更多有针对性的回答:你想做什么?为什么要将WordCount作为类型参数?如何实例化新的WordCountMap?我认为需要提供第二个参数。WordCountMapYea最好去掉泛型类型。另外,我们本可以将WordCountMap实现为字典,但在这么晚的时候,我宁愿不使用泛型类型。无论如何,谢谢。是的,最好去掉泛型类型。另外,我们本可以将WordCountMap实现为字典,但在这么晚的时候,我宁愿不使用泛型类型。谢谢你。
public class WordCountMap<V extends Number> {}
public class WordCountMap {
...
private class TreeNode {
...
private int count;
}
}