CodeManiak
CodeManiak

Reputation: 1953

How to create a custom list of objects in Java?

Arraylists use the following syntax: ArrayList<Object> = new ArrayList<Object>; I need to add a constructor to my GameList class that allows you to specify what type of list to create. I don't understand how to make my class capable of being defined like this:

GameList<objectType> = new GameList();

All of my objects in the game will descend from the gameobject class.

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;
    }
}

Upvotes: 2

Views: 10173

Answers (1)

Kayaman
Kayaman

Reputation: 73528

What you're looking for is Generics. The syntax would be

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

Upvotes: 5

Related Questions