如何在Java中创建自定义对象列表?

时间:2013-07-23 13:27:07

标签: java arraylist

Arraylists使用以下语法:ArrayList<Object> = new ArrayList<Object>; 我需要在GameList类中添加一个构造函数,允许您指定要创建的列表类型。我不明白如何使我的类能够像这样定义:

GameList<objectType> = new GameList();

游戏中的所有对象都将来自游戏对象类。

public class GameObject
{
    String name;
    public GameObject
    {
        name = "Stat";
    }
    public String getName()
    {
        return name;
    }
    public void setName(String newName)
    {
        name = newName;
    }
}

public class GameList
{
    GameObject[] theList;
    public GameList(int size)
    {
        theList = new GameObject[size];
    }
    public GameObject parseList(String objectName)
    {
        for(int i = 0; i < theList.length; i++)
            if(theList[i].getName() == objectName)
                return theList[i];
        return null;
    }
}

1 个答案:

答案 0 :(得分:4)

您正在寻找的是Generics。语法是

public class GameList<T> {
    T[] theList;
    ...