1

I am working on inserting a list of array inside an object. Using that object I have created, I am planning to use it inside another object as it is required to use it in my JTable.

This is my object class.

class MyData {
private String name;

public MyData(String name) {
    this.name = name;
   }
}

My main class is:

    String[] tt = {"aa"};
    MyData[] thePlayers = new MyData[0];
        for(int i = 0;i < tt.length;i++){
            thePlayers[i] = new MyData(tt[i]);
        }

    Object[][] data = {{"2"}};
    String[] headers = { "Income Type" };
    JTable table = new JTable(data, headers);

I am receiving this error on my system Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

What might be the cause of it? Ive tried all means, but I still cant figure it out.

UPDATE

I encounter a different hurdle which is initializing Object[][].

Example :

Object[][] data;

How do we initialize this in a forloop using above code we have applied in ThePlayers?

Lastly, when i run the program, it didnt display as what is specified in the array. enter image description here

  • 8
    With `new MyData[0];` you are creating an array of length zero. You need to create an array with the appropriate length. For example: `new MyData[1];` – Jesper Jun 10 '19 at 07:43
  • For convenience, recommend to use ArrayList instead of String Array – CK Wong Jun 10 '19 at 07:49

2 Answers2

0

As said in comments but just initialize the MyData object array corresponding to input data array length

MyData[] thePlayers = new MyData[tt.length];
        for(int i = 0;i < tt.length;i++){
            thePlayers[i] = new MyData(tt[i]);
        }
TechFree
  • 2,600
  • 1
  • 17
  • 18
-1

Arrays in Java have static size. In the second line of your main class u declare thePlayers with size 0 - you won't be able to put anything in it. Simple fix is to initialize array with the appropriate size.

String[] tt = {"aa"};
MyData[] thePlayers = new MyData[tt.length];
for(int i = 0;i < tt.length;i++){
    thePlayers[i] = new MyData(tt[i]);
}

Object[][] data = {{"2"}};
String[] headers = { "Income Type" };
JTable table = new JTable(data, headers);

Other option would be to use something like a List with dynamic size.

Amongalen
  • 3,101
  • 14
  • 20