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?

10th Feb 2020, 4:59 PM
Алексей Ермаков
Алексей Ермаков - avatar
2 Respostas
+ 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.
10th Feb 2020, 9:13 PM
Tibor Santa
Tibor Santa - avatar
+ 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;
10th Feb 2020, 9:55 PM
Gabriel Ilie
Gabriel Ilie - avatar