0

i am making a game and it uses a gird i can implement it by extending arraylist for example:

public class Grid extends ArrayList<ArrayList<obj>> 
{
     public void addObj(Obj obj ,int x, int y)
     {
           get(x).set(y,obj);
     }
}

or should i do it by storing it

public class Grid
{
      private ArrayList<ArrayList<obj>> objs = new ArrayList<...>();

       public void addObj( Obj obj, int x, int y)
       {
          objs.get(x).set(y,obj);
       }
}

help plz

  • @Kayaman I don't think it's a duplicate question. That question is a generic approach about how to solve those problems, but you may use that Q/A to support your answer. – Luiggi Mendoza Jul 15 '14 at 17:21
  • There's no right answer. Technically, a grid "**is a[n]**" ArrayList, but I'd go for composition anyway. – keyser Jul 15 '14 at 17:22
  • @LuiggiMendoza Not a duplicate no, but the message is still pretty much the same. – Kayaman Jul 15 '14 at 17:27

3 Answers3

3

The latter, compositional approach. ArrayList is how you choose to implement Grid now, but you might want to used Map or a different List type in the future.

Plus, some of ArrayList's methods are likely meaningless in the context of a Grid, e.g. subList.

bdkosher
  • 5,753
  • 2
  • 33
  • 40
1

In this case, it is better to use composition over inheritance. You should only make your class to extend from ArrayList (or any other class in the Java Collection Framework) in case you need to alter specific behavior of that class like add method.

By the way, you should declare the variable as List instead of ArrayList. Always code oriented to interfaces rather than specific implementation classes.

The code should look like this:

public class Grid {
    private List<List<obj>> objs = new ArrayList<List<obj>>();
    public void addObj( Obj obj, int x, int y) {
        objs.get(x).set(y,obj);
    }
}

More info:

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
1

Does Grid satisfy the following : Grid-is-a-ArrayList ? I would say not.

I would much rather use composition in this case. Your grid will provide a completely different (richer?) interface to a list.

Note that if you really need List semantics, you can implement the interface java.util.List on your Grid without actually inheriting the implementation. That will give you your desired contract but leaving the implementation up to you (whether you choose to delegate to a real list or not...)

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440