我有以下内容:
String[][] content = {
{"c","d", "2"},
{"e","f", "3"},
{"g","h", "4"},
{"i","j", "5"}} ;
如何在现有元素中添加一些1x3元素?
答案 0 :(得分:2)
public static void main(String[] args) {
String[][] content = {
{"c","d", "2"},
{"e","f", "3"},
{"g","h", "4"},
{"i","j", "5"}};
String[][] newContent = {{"p","a", "3"}};
System.out.println(Arrays.deepToString(append(content, newContent)));
}
public static String[][] append(String[][] a, String[][] b) {
String[][] result = new String[a.length + b.length][];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
return result;
}
<强>输出强>
[[c, d, 2], [e, f, 3], [g, h, 4], [i, j, 5], [p, a, 3]]
另一项输入
String[][] content = {
{"c","d", "2"},
{"S","2"},
{"i","j", "5"},{"p","1"}};
String[][] newContent = {{"p","a", "3"},{"k","3"}};
<强>输出强>
[[c, d, 2], [S, 2], [i, j, 5], [p, 1], [p, a, 3], [k, 3]]
答案 1 :(得分:0)
这很麻烦,涉及创建整个数组的副本,因此无法定期执行:
String[][] content = {
{"c","d", "2"},
{"e","f", "3"},
{"g","h", "4"},
{"i","j", "5"}};
content = Arrays.copyOf(content, content.length + 1);
content[content.length - 1] = new String[] { "k", "l", "6" };
但是你可以使用List:
List<String[]> list = new ArrayList<>();
Collections.addAll(list, content);
list.add(new String[] { "k", "l", "6" });
通过以下操作:
String[] row = list.remove(2);
list.get(1)[3]; // Getting
list.add(0, row); // Adding at an index