asma
asma

Reputation: 113

JTable two-dimensional object array

May this question is repeated but I tried most of the solution but none of them fit in my problem. Referring to this page : https://docs.oracle.com/javase/tutorial/uiswing/components/table.html

I want to create the JTable to read from objects from my custom class.As an initial step, I want to test the looping with the JTable. As follow:

Object[][] tripsData =new Object[3][6];
for(int j=0; j< 3;j++)
        for(int i =0; i< 6;i++)
        {   tripsData[j][i]= new Object[] {"Kathy", "Smith","wait",  "Snowboarding", 5, "false"};
        }

The code works fine except the output it shows like this:

 [Ljava.lang.Object;@41488024
 [Ljava.lang.Object;@54c83ae1
 [Ljava.lang.Object;@161a4f2c

I tried to use, toString() and valueOf(), but the same thing. Any suggestion to solve

Upvotes: 0

Views: 142

Answers (2)

evnica
evnica

Reputation: 320

The problem is you are creating a three-dimensional array instead of the 2D that you need. In your code, you use

tripsData[j][i]= new Object[] {"Kathy", "Smith","wait",  "Snowboarding", 5, "false"};

thus "Kathy" in the resulting Object has an index [j][i][0], "Smith" has an index [j][i][1] and so on. Populate your array like so:

Object[][] tripsData =new Object[3][6];
        for(int j=0; j< 3;j++) {
            tripsData[j] = new Object[]{"Kathy", "Smith", "wait", "Snowboarding", 5, "false"};
        }

Then both this

    for (Object[] row : tripsData) {
        for (int j = 0; j < data[0].length; j++) {
            System.out.print(row[j]);
            System.out.print("\t");
        }
        System.out.print("\n");
    }

and this

for (Object[] row : tripsData) {
    System.out.println(Arrays.toString(row));
}

will work fine

Upvotes: 1

You can use Arrays.toString(), somewhat similar to this snippet:

    Object[][] arr = new Object[2][2];
    arr[0][0] = "00";
    arr[0][1] = "01";
    arr[1][0] = "10";
    arr[1][1] = "11";
    System.out.println(Arrays.toString(arr[0]));
    System.out.println(Arrays.toString(arr[1]));

This will print

[00, 01]
[10, 11]

Upvotes: 0

Related Questions