【发布时间】:2020-12-26 21:59:37
【问题描述】:
public class Main{
private MyQueue queue = null;
private MyStack stack = null;
private MyList list = null;
public static void main(String args[]){
Main m = new Main();
m.run();
}
public void run(){
// only one data structure is not null.
// for example, let's suppose that it's queue
this.queue = new MyQueue();
int intToAdd = 6; // I want to add this number
this.selectStruct().insert(intToAdd); // I want to invoke the "insert" method of the current data structure in use
}
private <T> T selectStruct(){ // this should check with data structure is in use (so which of them is not null) and then return the reference
if (this.queue!=null){
return this.queue;
}
if (this.stack!=null){
return this.stack;
}
if (this.list!=null){
return this.list;
}
}
}
我想使用这个名为selectStruct 的方法来选择当前正在使用的数据结构并返回引用。然后从这个引用中调用insert 调用正确类的正确插入方法。
问题是我有几个错误。我从来没有使用过泛型,所以我有点困惑。
$ javac Main.java
Main.java:22: error: incompatible types: MyQueue cannot be converted to T
return this.queue;
^
where T is a type-variable:
T extends Object declared in method <T>selectStruct()
Main.java:25: error: incompatible types: MyStack cannot be converted to T
return this.stack;
^
where T is a type-variable:
T extends Object declared in method <T>selectStruct()
Main.java:28: error: incompatible types: MyList cannot be converted to T
return this.list;
^
where T is a type-variable:
T extends Object declared in method <T>selectStruct()
Main.java:17: error: cannot find symbol
this.selectStruct().insert(intToAdd);
^
symbol: method insert(int)
location: class Object
4 errors
【问题讨论】: