4

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.

4

2 回答 2

4

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();
}
于 2012-12-05T16:54:24.923 回答
2

something like this?

public Object[][] getStockTable() {
    ArrayList<Details> details = getDatailsList();
    Object[][] result = new Object[details.size()][];
    for (int i = 0; i < details.size(); i++) {
        Details detail = details.get(i);
        Object[] det = new Object[4];
        det[0] = detail.getName();
        det[1] = detail.getPrice();
        det[2] = detail.quan();
        det[3] = detail.totalValue();
        result[i] = det;
    }
    return result;
}
于 2012-12-05T16:54:46.257 回答