简体   繁体   English

Java,如何将值添加到对象数组

[英]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 . 这是需要使用listData的功能。

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

but how can I add values into listData from a for loop? 但是如何从for循环中将值添加到listData中呢?

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
 }

Arrays are fixed sized , after creating the array Object, you can't update it's size/ enlarge it's size. 数组是固定大小的 ,创建数组Object后,您无法更新它的大小/不能放大它的大小。 So the purpose to be dynamic size or auto growing sized, you need to use List ie. 因此,要达到动态尺寸或自动增长尺寸的目的,您需要使用List即。 ArrayList . 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 . 但是需要将此ArrayList传递给采用array的函数,因此,您可以将ArrayList转换为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? 但是如何从for循环中将值添加到listData中呢? 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有一个addRow方法,该方法接受一个数组或一系列对象,因此只需使用:

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

Should work. 应该管用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM