1

I need to add dynamically a cell to a matrix or an Object[][] to be more precise, the size of the Object's columns is 2 and the rows need to grow every time i need to add an entry.

I found this answer but the problem is that it handles a one dimensional arraylist, and i don't how to handle a two dimensional arraylist.

So the question exactly is: How can i add dynamicaly and in ascending order a row to an matrix of Objects or to an arraylist?

Any help would be appreciated and thank you in advance.

Community
  • 1
  • 1
user3610008
  • 79
  • 2
  • 11
  • 1
    You shouldn't use arrays, but use `List`s, for example, here you may use `ArrayList` or (better) `ArrayList columns;`, where `Column` is a class, which contains these two items. – Dmitry Ginzburg Jul 08 '14 at 13:32
  • "the size of the Object's columns is 2 and the rows need to grow every time i need to add an entry." I don't understand this. – aliteralmind Jul 08 '14 at 13:38
  • 2
    @aliteralmind this would make sense, when you change rows with cols and vice-versa. – Dmitry Ginzburg Jul 08 '14 at 13:40
  • 1
    You should look at this question: http://stackoverflow.com/questions/24526019/how-to-make-arraylist-that-work-as-two-dimentional-array-in-java/24526104#24526104 – EpicPandaForce Jul 08 '14 at 13:40

1 Answers1

2

It works the same way as the answer you referenced, only you would have two nested arraylists as such:

List<List<Item>> matrix = new ArrayList<List<Item>>();

To get one dimension, just do:

matrix.get(x);

To get the second one, just do:

matrix.get(x).get(y);

To add, you can just add "rows":

matrix.add(new ArrayList<Item>());

If your second dimension is static, an easier route would just be to do:

List<Object[]> matrix;

But this would mean you need a set size for the Object[] array.

Xinzz
  • 2,242
  • 1
  • 13
  • 26
  • 1
    Why not `List> arrayList = new ArrayList>();` ? – EpicPandaForce Jul 08 '14 at 13:36
  • Works as well, just used a specific implementation as an example. – Xinzz Jul 08 '14 at 13:37
  • 1
    I think, `Item` is more correct example-name, than `Items` here. – Dmitry Ginzburg Jul 08 '14 at 13:37
  • Updated answer as per suggestions – Xinzz Jul 08 '14 at 13:38
  • Oh wait, after the last edit your answer contain the mistake, it didn't before: `ArrayList` IS NOT `List`. So, either it should be `ArrayList` at the right side (preferrable) or `List>` at the right side. For the explanation look @ http://www.coderanch.com/t/591388/java/java/Covariance-Contravariance-Invariance – Dmitry Ginzburg Jul 08 '14 at 14:35
  • For the List lets say i want to access the cell {3, 1}, do i do matrix.get(3)[1]? – user3610008 Jul 08 '14 at 15:03
  • Remember that indices start at 0. {x, y} would be matrix.get(x)[y-1] (this is assuming your matrix starts at 1). Also remember to initialize and add the array before indexing or you will get null pointer exceptions. – Xinzz Jul 08 '14 at 15:30