我想编写一个模板HashTable
,它可以存储任何类型的记录。我正在使用 Java 泛型来执行相同的操作。以下是 HashTable
中的代码片段:
class MyHashTable <T, K>{
private int size;
private Vector <Vector <T>> table;
public MyHashTable(int s) {
size = s;
table = new Vector(size);
}
void insert(T newRecord) {
int hash = newRecord.getHash(size);
...
}
...
}
以下是我要存储的记录类型的示例:
class Record {
private String name;
private String id;
public String getKey() {
return name;
}
public int getHash(int hash_table_size) {
int index = 0;
String key = getKey();
for(int i=0; i<key.length(); i++)
index += (int)key.charAt(i);
index = index % hash_table_size;
return index;
}
...
}
为了实例化 HashTable,我写道:
MyHashTable <Record, String> hashTable = new MyHashTable(50);
当我编译代码时,出现以下错误:
HashTableImplementation.java:63: error: cannot find symbol
int hash = newRecord.getHash(size);
^
symbol: method getHash(int)
location: variable newRecord of type T
where T is a type-variable:
T extends Object declared in class MyHashTable
我错过了什么吗?
最佳答案
您可以将定义更改为
class MyHashTable <T extends Record, K>
或在方法级别执行类似操作
<T extends Record> void insert(T newRecord) {
int hash = newRecord.getHash(size);
}
通过添加有界参数,您将指示您仅接受 Record 类型或其子类型。当您针对参数化类型调用特定于 Record 类的方法时,您需要使用它
关于Java 泛型 : cannot find symbol,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27648689/