0
How to add Object in object massive?
Java massive Objects There is an array of objects: Object [][] data1 = { {icon1, "text1"}, {icon1, "text2"}, {icon1, "text3"}, }; Where icon1 is given as: Icon icon1 = new ImageIcon ("pic.png"); How to add another new object to data1?
2 Respuestas
+ 1
Arrays have fixed sizes. If you initialize it like this, the array will be just as big as required to hold its content.
You could use a List instead that has dynamically changing size.
Or initialize the array to be bigger, so it can hold all possible values.
+ 1
You cannot add a new element because array length is immutable. if you know the array length you can do it like this:
Object [][] data1 = new Object[4][2];
for(int i = 0; i < 4; i++)
{
for(int y = 0; y < 2; y++)
{
if(y==0) {
data1[i][y] = icon1;
continue;
}
data1[i][y] = "text" + (i+1);
}
}
If you don't know the length you can do it like this:
Map<Icon,List<String>> map = new HashMap<>();
ArrayList<String> list = new ArrayList<>();
list.add("text1");
list.add("text2");
list.add("text3");
map.put(icon1,list);
Don't forget to:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;