-2

I have a little bit problem, about 2 Dimensional Array.

This is my example code:

Object data1[][] = {
        {icon.get(0), monster.get(0).getName(), monster.get(0).getAp(), monster.get(0).getHp(), monster.get(0).getDp(),},
        {icon.get(1), monster.get(1).getName(), monster.get(1).getAp(), monster.get(1).getHp(), monster.get(1).getDp(),},};

How to convert this adding values into a for loop?

  • monster is an ArrayList of Object Monster.
  • icon is an ArrayList of Object ImageIcon.
Stéphane Bruckert
  • 21,706
  • 14
  • 92
  • 130
Iman Tumorang
  • 131
  • 2
  • 9
  • 25
  • 9
    You forgot to ask a question... – assylias Dec 17 '14 at 15:36
  • Haha, sorry for that. the question is : how can i convert that into loop for, so that i can assign the value without access manually.. :) – Iman Tumorang Dec 17 '14 at 15:40
  • Your question looks like [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Can you tell us more about how are you going to use your array? – Pshemo Dec 17 '14 at 15:46
  • it's difficult to explain, plus more my bad english... :( I'll try: I have 2 array List 1. Array List of Monster 2. Array List of ImageIcon ImageIcon save the icon that the image's name retrieve from Monster And i will save both Array ImageIcon and Monster into new 2 Dimensional array this 2 dimensional array , will be the data to Jtable *how about this, still confuse about my question.. :( – Iman Tumorang Dec 17 '14 at 15:56

2 Answers2

0

Arrays are immutable in size, i.e. you cannot add a value to an array and increase it's size without creating a new array.

I would suggest using ArrayLists and then converting them with .toArray() if absolutely necessary.

Have a look at this question for an example:

How to create a Multidimensional ArrayList in Java?

Community
  • 1
  • 1
Erik Schmiegelow
  • 2,739
  • 1
  • 18
  • 22
0

If you are looking for making an array based on numbers of monsters without hard-coding you need to do this

int numOfMonsters = monster.size();
Object data1[][] = new Object[numOfMonsters][5];
for(int i = 0; i < numOfMonsters; i++){
    data1[i][0] == icon.get(i);
    data1[i][1] == monster.get(i).getName();
    data1[i][2] == monster.get(i).getAp();
    data1[i][3] == monster.get(i).getHp();
    data1[i][4] == monster.get(i).getDp();    
}
Dave P
  • 156
  • 1
  • 8