1

I'm having problems from getting data from a JTable. I need to save it to an ArrayList<String[]>. I do a loop of rows and columns but something is not working, it saves only the last row...

This is the function example:

private void saveTable(){

    ArrayList<String[]> tableSaved = new ArrayList<>();
    String[] rowSaved = new String[headerTable.length];
    String cellValue;

    for(int row=0;row<table.getModel().getRowCount();row++){
        for (int column=0; column<table.getModel().getColumnCount();column++){  
            cellValue = (String) table.getModel().getValueAt(row, column);
            rowSaved[column] = cellValue;

        }       
        tableSaved.add(rowSaved);
        // I check here if the output is correct, and It is.    
        System.out.println("GET");
        for(String s:rowSaved){
            System.out.print(s+" ");
        }
    }

    //When I check if the tableSaved is correct, It doesn't.
    System.out.println("");
    System.out.println("ACTUALLY SAVED");
    for (String[] row:tableSaved){          
        for (String s:){
            System.out.print(" "+s);
        }
        System.out.println("");
    }

I've tried this loop too

    int row=0;
    while (row<table.getModel().getRowCount()){ 
        int column=0;

        while (column<table.getModel().getColumnCount()){

            cellValue = (String) table.getModel().getValueAt(row, column);
            rowSaved[column] = cellValue;
            column++;
        }       
        tableSaved.add(rowSaved);
        row++;
    }

It returns the last row as many times as rows in the table... I've looking for an answer but I nothing solved the bug

This is an example screenshot

data from table returns

2
  • 1
    I think you need to add tableSaved.add(rowSaved); this inside a loop. Commented Mar 7, 2017 at 12:25
  • but It is inside the first loop... Commented Mar 7, 2017 at 12:30

1 Answer 1

2

The problem is here tableSaved.add(rowSaved); you are adding an array of strings, but you are keeping the reference of that array, and in the next iteration you are changing elements of that same array.

Create a new rowSaved = new Sting[] inside the loop when you begin reading the elements or after you add the array into the ArrayList.

After the line tableSaved.add(rowSaved); add this line rowSaved = new String[headerTable.length];

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I thought I could use a unique Array just overwriting the info each loop...
Nope! Have a look at this link javaworld.com/article/2077424/learn-java/…, it will help you understand why.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.