尝试在eclipse中解决有关在抽象类中使用泛型的警告。
下面是一个例子。请忽略错别字。我不得不重新输入它。代码编译得很好,这只是泛型问题。
这是我使用泛型的示例抽象类:
public abstract class myThing<T> { //myThings can be Integers, Character, or other
//will compare a local stored myThing instance with the passed myThing instance
public abstract boolean compare (myThing<T> theThing);
//returns the locally stored version of myThing
public abstract T getMyThing();
//sets the value of the local instance of myThing
public abstract setMyThing(T theValueOfMyThing)
}
现在我想创建一个存储和管理myThing对象的类
public class myThingList<myThing> {
private Vector<myThing> listOfMyThings; //a private array of myThings
public myThingList() { //constructor just initializes an empty array
listOfMyThings = new Vector<myThings>();
}
//add a passed myThing object to the list
public void addThingToList(myThing x){
listOfMyThings.Add(x);
}
//get a myThingObject at specified index from list
public myThing getItemOnMyList(int idx){
return listofMyThings.get(idx)
}
}
所以问题是我收到了myThing
中myThingList<myThing>
隐藏myThing<T>
的日食警告。
感谢
答案 0 :(得分:1)
使用myThing<T>
时,您需要声明类型T
。请记住,如果您正在创建地图列表,请将其声明为List<Map<String, Object>>
在这种情况下,您有几种选择。要么myThing的类型显式如下:
public class myThingList<myThing<SomeType>> {
private Vector<myThing<SomeType>> listOfMyThings; //a private array of myThings
public myThingList() { //constructor just initializes an empty array
listOfMyThings = new Vector<myThings<SomeType>>();
}
//add a passed myThing object to the list
public void addThingToList(myThing<SomeType> x){
listOfMyThings.Add(x);
}
//get a myThingObject at specified index from list
public myThing<SomeType> getItemOnMyList(int idx){
return listofMyThings.get(idx)
}
}
或者myThingList也是通用的,如下所示:
public class myThingList<T> {
private Vector<myThing<T>> listOfMyThings; //a private array of myThings
public myThingList() { //constructor just initializes an empty array
listOfMyThings = new Vector<myThings<T>>();
}
//add a passed myThing object to the list
public void addThingToList(myThing<SomeType> x){
listOfMyThings.Add(x);
}
//get a myThingObject at specified index from list
public myThing<SomeType> getItemOnMyList(int idx){
return listofMyThings.get(idx)
}
}
答案 1 :(得分:0)
您正在使用myThingList
作为T
类的类型参数的名称。请改用public class myThingList<myThing>{
private Vector<myThing> listOfMyThings;
。
更改
public class myThingList<T>{
private Vector<T> listOfMyThings;
到
T
并在整个课程中使用myThingList
。
如果myThing
仅用于存储Vector<myThing>
个对象,请将其删除,然后改用myThingList
。
无论哪种方式,您的Vector
课程都没有添加任何价值 - 它只是{{1}}上的薄贴面。