p3ace p3ace - 3 months ago 6
Java Question

Displaying the string values of 2 dimensional Object array

I am trying to display the contents of an array after iterating through rows and columns of a

JTable
. I tried
Arrays.toString(myTwoDimensionalArrayVariable)
but it won't display the string values.

My goal is to check duplicates for every column per row of a destination
JTable
when user tries to add row values from a source
JTable
that's why I want to display the contents of the array.

The values on columns are combination of
double
,
String
, and
int
.

int myRowCount = aJTableParameter.getRowCount();
int myColumnCount = aJTableParameter.getColumnCount();
Object[][] myRowValues = new Object[myRowCount][myColumnCount];


for (int j = 0; j < myRowCount; j++) {
for(int i = 0; i< myColumnCount; i++){
myRowValues[j][i] = aDestinationTable.getValueAt(j, i);
}
}

System.out.println(Arrays.toString(myRowValues));

if (Arrays.asList(myRowValues).contains(column1Value)
&& Arrays.asList(myRowValues).contains(column2Value)
&& Arrays.asList(myRowValues).contains(column3Value)
&& Arrays.asList(myRowValues).contains(column4Value)) {
JOptionPane.showMessageDialog(null, "Duplicate, try again.");
}else{
//do something else
}


I only get this output:

run:
Successfully recorded login timestamp
[]
[[Ljava.lang.Object;@35fa3ff2]
[[Ljava.lang.Object;@407c448d, [Ljava.lang.Object;@1e78a60e]


Is there any other alternative than using 2 Dimensional Arrays?

I'd appreciate any help.

Thanks.

Answer

IFF your JTable cells contain only Strings, you can define your array as String[][] instead of Object[][] and fill it with your JTable contents using aDestinationTable.getValueAt(j, i).toString().

EDIT: since that's not the case (as per your comment), it's probably better to use a List, like this:

    List<List<Object>> objectList = new ArrayList<>();
    for (int j = 0; j < 2; j++) {
        objectList.add(j, new ArrayList<>());
        for (int i = 0; i < 2; i++) {
            if (i==0) objectList.get(j).add("string" + j + i);
            if (i==1) objectList.get(j).add((double) 37.8346 * j * i);
        }
    }

    System.out.println("OBJECT LIST: "+objectList);

Output:

OBJECT LIST: [[string00, 0.0], [string10, 37.8346]]

Your code should look like this, then:

    List<List<Object>> myRowValues = new ArrayList<>();
    for (int j = 0; j < myRowCount; j++) {
        myRowValues.add(j, new ArrayList<>());
        for (int i = 0; i < myColumnCount; i++) {
            myRowValues.get(j).add(aDestinationTable.getValueAt(j, i));
        }
    }

    System.out.println(myRowValues);