[英]Java: how to access inner class's own type
I'm trying to implement a basic symbol table using array. 我正在尝试使用数组实现基本的符号表。
When I try to implement a get method whose return type is defined in my inner class, but java does not allow me to do that. 当我尝试实现其返回类型在我的内部类中定义的get方法时,但是java不允许我这样做。 H H
How can i achieve that? 我该如何实现?
ERROR: cannot resolve symbol 'Key' 错误:无法解析符号“键”
public class ST2 {
Item[] items;
int N;
public class Item<Key extends Comparable, Value>{
public Key key;
public Value value;
public Item(Key key, Value value){
this.key = key;
this.value = value;
}
//Some other methods.
}
public ST2(int capacity){
items = (Item[])new Object[capacity];
}
//Some other Method
public Key get(Key key){ //ERROR HERE: cannot resolve symbol 'Key'
return items[some_index].key;
}
You need to define the Key
on ST2
, not on Item
: 您需要在ST2
而不是Item
上定义Key
:
public class ST2<K extends Comparable<K>, V> {
Item[] items;
int N;
public class Item {
public K key;
public V value;
public Item(K key, V value) {
this.key = key;
this.value = value;
}
}
public ST2(int capacity) {
items = (Item[]) new Object[capacity];
}
public K get(int index) {
return items[index].key;
}
}
Also, generics are usually single letters. 同样,泛型通常是单个字母。
I assume that you're doing this as some sort of exercise/homework, because there already is a Java class that maps (comparable) keys to values: http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html 我假设您正在做某种练习/作业,因为已经有一个Java类将(可比较)键映射到值: http : //docs.oracle.com/javase/7/docs/api/的java / UTIL / TreeMap.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.