Search code examples
javaarraysarraylistlibgdx

Overriding ArrayList<> for Specific Object for libGDX Game


Please go easy on me if this is a simple question (it's my first time asking one), I am still a beginner with libGDX and working on my first game.

Background: I need to keep a list of "Gem" objects for a game I am working on in a list. Currently I am using an ArrayList, however I am using multiple helper methods. Unfortunately, because I am only using a generic ArrayList all of these helper methods have to be in my main game class.

My Question: In an effort to keep my code as clean as possible, is there a way to override the entire ArrayList class just for my "Gem" object, so that I can add all of my helper methods, and still be able to use the Java defined ArrayList<> for other objects? Or do I have to create a type of pseudo ArrayList class that implements all the methods associated with an ArrayList? This just seems very tedious.


Solution

  • Your question is a bit vague. Do you want to extend a ArrayList so that you can only put in instances of the class Gem? If so you can easily do it like this:

    public class GemList extends ArrayList<Gem> {
     //All your helper methods
    }
    

    And use it like this:

    GemList gemList = new GemList();
    gemList.add(new Gem());