Michael Wiggins
Michael Wiggins

Reputation: 112

Java remove row from multidimensional array

I have an interesting dilemma;

I have a String[][] pulled from a MySQL database. For simplicity, I have printed the contents using Arrays.deepToString(<arrayname>):

[[1, gimley, <sanitised>, <sanitised>, <sanitised>, <sanitised>, 1994-10-11, <sanitised>, 2015-02-20 08:55:36.0], 
[2, Eris, Exotic, <sanitised>, <sanitised> <sanitised> <sanitised>, <sanitised>, 1996-02-15, <sanitised>, 2015-02-24 13:02:00.0], 
[3, Macca, Maccan, <sanitised>, <sanitised>, <sanitised>, 1996-11-11, University, Probably on Destiny, 2015-02-24 13:03:17.0], 
[4, <sanitised>, bacon, standard, <sanitised>, <sanitised>, 1996-03-12, <sanitised> or <sanitised>; depends, 2015-02-26 15:44:28.0]]

My question is: How can I remove one of the rows of the array-of-arrays, and replace the existing database with the contents of a new array-of-arrays? I understand that this is bad practice as I can just update the table directly, but this exercise requires me to do this method.

Upvotes: 0

Views: 1545

Answers (1)

Andreas
Andreas

Reputation: 313

do you mean something like this?

public class TestClass {

public static final String[][] removeRow( String[][] source, String rowName ) {
    boolean rowFound = false;
    for ( int i = 0; i < source.length; i++ ) {
        if ( source[ i ][ 0 ].equals( rowName ) ) {
            rowFound = true;
        }
    }
    if ( !rowFound ) {
        return source;
    }

    String[][] result = new String[ source.length - 1][ source[ 0 ].length ];
    int resultIndex = 0;
    for ( int i = 0; i < source.length; i++ ) {
        if ( !source[ i ][ 0 ].equals( rowName ) ) {
            System.arraycopy( source[ i ], 0, result[ resultIndex ], 0, source[ i ].length );
            resultIndex++;
        } 

    }

    return result;
}

@Test
public void test() {
    String[][] source = { 
            { "1", "one", "I", "eins" }, 
            { "2", "two", "II", "zwei" }, 
            { "3", "three", "III", "drei" }, 
            { "4", "four", "IV", "vier" } 
    };

    String[][] result = removeRow( source, "2" );
    assertEquals( "{[1, one, I, eins][3, three, III, drei][4, four, IV, vier]}", toString( result ) );

    result = removeRow( source, "rowNotIn" );
    assertEquals( "{[1, one, I, eins][2, two, II, zwei][3, three, III, drei][4, four, IV, vier]}", toString( result ) );
}

private String toString( String[][] source ) {
    StringBuffer sb = new StringBuffer();
    sb.append( "{" );
    for ( int i = 0; i < source.length; i++ ) {
        sb.append( Arrays.toString( source[ i ] ) );
    }
    sb.append( "}" );
    return sb.toString();
}

}

Upvotes: 1

Related Questions