how to add ArrayList<String> to table?

3k Views Asked by At

From the following array list , i need to remove the comma and add every element to an cell in JTable. For example, My JTable - will have 12 columns and row 1 should be be filled 0 0 0 ....

Request you to help me in removing the commas from the list and add elements to the cell in JTable.

//code

ArrayList list = new ArrayList();

list.add("0 , 0 , 0 , 4 , 2 , 0 , 2 , 0 , 1 , 0 , 0 , 0");

list.add("1 , 0 , 0 , 4 , 2 , 0 , 3 , 0 , 1 , 0 , 0 , 1");

list.add("2 , 0 , 0 , 4 , 1 , 0 , 2 , 0 , 1 , 0 , 0 , 0");

2

There are 2 best solutions below

4
On BEST ANSWER
ArrayList list = new ArrayList();

list.add("0 , 0 , 0 , 4 , 2 , 0 , 2 , 0 , 1 , 0 , 0 , 0");

list.add("1 , 0 , 0 , 4 , 2 , 0 , 3 , 0 , 1 , 0 , 0 , 1");

list.add("2 , 0 , 0 , 4 , 1 , 0 , 2 , 0 , 1 , 0 , 0 , 0");

//now go through the ArrayList and split each entry by ',' and add to a 2D array, JTable

int[][] JTable = new int[list.size()][];
for (int row = 0; row < list.size(); row++) {
    //get an item from the ArrayList
    String rowString = list.get(row);
    //remove all the whitespaces from the string
    rowString = rowString.replaceAll("\\s+","");
    //split the string using "," as a delimiter
    String[] items = rowString.split(",");
    JTable[row] = new int[items.length];
    for (int col = 0; col < items.length; col++) {
        JTable[row][col] = Integer.parseInt(items[col]);
    }
}
0
On

The following code works fine! Posting the code to help fellow programmers ....

//new logic for (int row = 0; row < recommendedTestSet.size(); row++)

    {

        String rowString = recommendedTestSet.get(row);

        rowString = rowString.replaceAll("\\s+","");

        String[] items = rowString.split(",");

        rtsTable.addRow(items);
    }