Yung A
Yung A

Reputation: 239

Java, How do i add values to Object array

I need to add values to an array of objects dynamically and pass that array variable to a function.

If I add values manually it works fine.

Object[][] listData = {{"Cheese", "Pepperoni", "Black Olives"},{"Cheese",    
"Pepperoni", "Black Olives"}};

This is the function that needs to use listData .

TableModel tblModel = new DefaultTableModel(new String[]{"Date", "Action", "Amount"}, listData); 

but how can I add values into listData from a for loop?

ArrayList<Map<String, Object>> sampleArray =   (ArrayList)myPremiumspaid.get("Data"); 
for(int x =0; x<sampleArray.size(); x++)
 {
    //sampleArray.get(x).get("YearMonth");
   //listData[][] = "";  stuck here
 }

Upvotes: 2

Views: 23610

Answers (1)

CrawlingKid
CrawlingKid

Reputation: 994

Arrays are fixed sized, after creating the array Object, you can't update it's size/ enlarge it's size. So the purpose to be dynamic size or auto growing sized, you need to use List ie. ArrayList.

Object[][] listData = {{"Cheese", "Pepperoni", "Black Olives"},{"Cheese",    
"Pepperoni", "Black Olives"}};

Instead:

List<List<Object>> listData=new ArrayList<List<Object>>();
listData.add(Arrays.asList("Cheese", "Pepperoni", "Black Olives"));
listData.add(Arrays.asList("Cheese", "Pepperoni", "Black Olives"));

But this ArrayList needs to be passed into a function which is taking array, so, you could convert the ArrayList to array object.

TableModel tblModel = new DefaultTableModel(new String[]{"Date", "Action", "Amount"}, (Object[][]) listData.toArray()); 

but how can I add values into listData from a for loop? Now you could do it as follows:

ArrayList<Map<String, Object>> sampleArray =   (ArrayList)myPremiumspaid.get("Data"); 
for(int x =0; x<sampleArray.size(); x++)
 {
    //sampleArray.get(x).get("YearMonth");
   listData.get(x).add(sampleArray.get(x).get("YearMonth"));
 }

Codename One's DefaultTableModel has an addRow method that accepts an array or series of Objects so just using:

((DefaultTableModel)tblModel).addRow("Cheese", "Pepperoni", "Black Olives"); 

Should work.

Upvotes: 4

Related Questions