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

Cod*_*iak 2 java arraylist

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

GameList<objectType> = new GameList();
Run Code Online (Sandbox Code Playgroud)

我在游戏中的所有对象都来自于游戏对象类。

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Kay*_*man 5

你要找的是Generics. 语法是

public class GameList<T> {
    T[] theList;
    ...
Run Code Online (Sandbox Code Playgroud)