1

I know that there were other questions related to this topic. But this is a little different.

Immagine that you have a program that gets every some amount of time an 2d Object (Object[][]) from the excel and it pass this to one method; this method needs to concatenate this 2d Object, so when it gets a flag that there is no more input, it passes this potentially big 2d object as a result to some other method...

1) You don't know how many excel documents will be sent , so how many 2d object will you get

2) every 2d object can have different num of columns and rows (ok this is not a big problem)

Is there a way in java to concatenate 2d objects into one? Wihout "killing" the memory.

Looking at this accepted anwer How do you append two 2D array in java properly? there is an append method, but each time it is called (and in this described case we don't know how many times could be called), it recreates an 2d array, and in my opition is not a best practice for this solution.

Looking at this accepted solution How to concatenate two-dimensional arrays in Java there is used an arraycopy solution, which how i understood is something similar to the previous solution... maybe a little better.

I know that would be possible to use some lists that could somehow rappresents this 2d object, or be parsed at the end in the 2d object, but: is there any way in java (good practice) to concatenate dinamically unown number of 2d object into 1?

tnx

Community
  • 1
  • 1
lucidBug
  • 197
  • 1
  • 10

1 Answers1

0

It look like you need ArrayList< ArrayList < Object > > instead of Object[][]. If you use ArrayList, the different num of columns and rows aren't problems at all, and you not "killing" the memory if you use addAll method. Moreover, you could use a core Java methods to concat ot ArrayLists without create your own manual methods.

For example, you can use something like this:

public List<ArrayList<Object>> concat (List<ArrayList<Object>> list1, List<ArrayList<Object>> list2) {
   if(list1.size() > list2.size()) {
      List<ArrayList<Object>> listBig = new ArrayList(list1); // or just list1 if we can change list1
      List<ArrayList<Object>> listSmall = list2;
   } else {
      List<ArrayList<Object>> listBig = new ArrayList(list2); // or just list1 if we can change list1
      List<ArrayList<Object>> listSmall = list1;
   }

   for(int i = 0; i < listSmall.size(); i++) {
      listBig[i].addAll(listSmall[i]); 
   }
   return listBig;
}
Slava Vedenin
  • 58,326
  • 13
  • 40
  • 59
  • Tnx, but: **1)** every time I call concat (and can be several times) , I need to make _new ArrayList (list1)_ ? (if every time first "if" passes) **2)** the for loop is not good right? cause it can overwrite the listBig, the listBig[i] must start at the last element of listBig? – lucidBug Dec 09 '15 at 09:14