gpt4 book ai didi

Java从多维数组中删除行

转载 作者:行者123 更新时间:2023-12-01 11:51:44 26 4
gpt4 key购买 nike

我有一个有趣的困境;

我有一个从 MySQL 数据库中提取的 String[][]。为简单起见,我使用 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]]

我的问题是:如何删除数组数组的一行,并用新数组数组的内容替换现有数据库?我知道这是不好的做法,因为我可以直接更新表,但这个练习需要我执行此方法。

最佳答案

你的意思是这样的吗?

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();
}

}

关于Java从多维数组中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28763590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com