gpt4 book ai didi

java - 创建具有相同类型参数的类型变量

转载 作者:行者123 更新时间:2023-11-29 03:09:08 24 4
gpt4 key购买 nike

我必须创建一个二叉搜索树,它将 WordCount 对象作为键,并将该词添加到 BST 的次数作为值。在我的代码中,我有类(class):

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
}
}

当我尝试编译代码时出现错误:

WordCount extends Object declared in class WordCountMap

我尝试了 @SuppressWarnings("rawtypes") 但仍然导致相同的错误。

最佳答案

看起来您没有正确使用泛型。

假设您用 T 替换了 WordCount 的所有实例(无论哪种方式都是同一个程序)。在 incrementCount() 中,您有 wordItem = new T(word); 这行,但这没有意义,因为您不知道 T 有一个带有 String 参数的构造函数。

由于看起来您总是希望键的类型为 WordCount,因此您可能需要按如下方式声明该类。

public class WordCountMap<V> {}

但是你希望计数的类型是任何对象吗? count的类型可以是String、Stack、InputStream吗?为了安全起见,您可以将类声明为 . . .

public class WordCountMap<V extends Number> {}

但即便如此,您为什么希望计数是通用的?您是否打算将这门课扩展到另一门课?计数类型不能只是 int 或 long 有什么原因吗?我会摆脱所有泛型,只使用一些原始数字类型来计数

public class WordCountMap { 
...
private class TreeNode {
...
private int count;
}
}

关于java - 创建具有相同类型参数的类型变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30404229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com