Creating Object[][] Types On The Fly

java, list, object

Solution

An `Object[][]` is simply an array of `Object[]`, so the OO way to do it would be to add a method to `Detail` that creates a single "row" `Object[]`

public Object[] toRow() {
  return new Object[] { getName(), String.valueOf(getPrice()) /* etc. */ };
}

then collect those up in `getStockTable`

Object[][] tbl = new Object[myDetails.size()][];
int row = 0;
for(Detail d : myDetails) {
  tbl[row++] = d.toRow();
}

Problem

Here is my define class, I haven't included the getting code to keep it short and sweet. ``` public class Details() { String name; double price; int quan; double totalValue; public String getName(); public double getPrice(); public int quan(); public double totalValue(); } ``` This is how I hold my list of details ``` ArrayList<Details> myDetails = new ArrayList<Details>(); ``` This is the function I would like to use to make my table rows/columns Here I would like to be able to iterate though my details table to produce something similar to below. ``` public Object[][] getStockTable() { Object[][] dynamicObject = new Object[][] { { "Name1", "Price1", "Quan1", "TV1" }, { "Name2", "Price2", "Quan2", "TV2" }, { "Name3", "Price3", "Quan3", "TV3" } }; //But how do this by iterating through rather than manually like above^ return dynamicObject; } ``` This is how I'm setting the row/columns for the table ``` dm.setDataVector(getStockTable(), new Object[] { "Name","Price", "Quan", "Total Value" }); ``` After some messing around I've not managed to come up with a way of doing this. Please don't just spoon feed me an answer, I would like to be able to understand how to do it rather than having it done for me.

Original source