使用带有泛型的抽象类

时间:2018-01-29 21:27:06

标签: java generics

尝试在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)
    }
}

所以问题是我收到了myThingmyThingList<myThing>隐藏myThing<T>的日食警告。

我明白了。 MyThing是一个抽象类,在扩展之前不会定义。那我该如何解决这个问题呢?显然我在使用泛型时在做错了。

PS:我可以让程序在没有它们的情况下正常运行。只需要小心铸造,但想看看泛型是否可以帮我清理一下程序。

感谢

2 个答案:

答案 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

OR

如果myThing仅用于存储Vector<myThing>个对象,请将其删除,然后改用myThingList

无论哪种方式,您的Vector课程都没有添加任何价值 - 它只是{{1}}上的薄贴面。