using insertRow() with a Table

edited October 2013 in How To...

Can someone provide an example of the insertRow() function with a Table? I can't search the old forums and I'm just looking for a simple example to get me on my way. I looked up the Table Class and I'm stuck.

Answers

  • Looking at the source code I get the impression it should be something like this:

    Table table;
    
    void setup() {
      table = new Table();
      
      table.addColumn("species", Table.STRING);
      table.addColumn("name", Table.STRING);
        
      TableRow a = table.addRow();
      a.setString("species", "A");
      a.setString("name", "a");
      
      TableRow b = table.addRow();
      b.setString("species", "C");
      b.setString("name", "c");
      
      String[] o = {"B", "b"};
      table.insertRow(1, o);
    }
    

    But it gives an ArrayIndexOutOfBoundsException.

    Anyone who has used insertRow()?

  • Answer ✓

    Indeed, it fails. I tried a variant:

    Table table;
    
    void setup() {
      table = new Table();
    
      table.addColumn("species", Table.STRING);
      table.addColumn("name", Table.STRING);
    
      TableRow a = table.addRow();
      a.setString("species", "A");
      a.setString("name", "a");
    
      String[] c = { "C", "c" };
      table.addRow(c);
    
      println(table);
      table.save(System.out, "csv");
    
      String[] b = { "B", "b" };
      table.insertRow(0, b);
    }
    

    With same outcome... :-(

    This API is still young, still lacking documentation, and perhaps under-tested. I haven't found an example of usage of insertRow(), for example.

    Perhaps we should raise a bug report about this function?

    Yes, the bug is in the line:

    System.arraycopy(columns[col], insert, stringTemp, insert+1, (rowCount - insert) + 1);
    

    If we insert at pos 1 with two rows, we must copy 1 element at insert+1, while rowCount - insert + 1 is 2.

  • Thanks @hamoid and @Philho. So it wasn't just me then. I made a few attempts with no results. I came up with a function that is a bit clunky, by copying and shifting rows down, but it works. Thanks for looking into it.

  • Looks like with the new beta of 2.1, the insertRow() function is working just fine!

Sign In or Register to comment.