我有以下幾點:如何將元素追加到String [] []?
String[][] content = {
{"c","d", "2"},
{"e","f", "3"},
{"g","h", "4"},
{"i","j", "5"}} ;
我能做些什麼,以添加一些元素×3到已經存在的呢?
我有以下幾點:如何將元素追加到String [] []?
String[][] content = {
{"c","d", "2"},
{"e","f", "3"},
{"g","h", "4"},
{"i","j", "5"}} ;
我能做些什麼,以添加一些元素×3到已經存在的呢?
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]]
@uksz如果我的回答是有用的,那麼請upvote並接受我的答案,提前致謝! –
這很麻煩,涉及創建整個數組的一個副本,因此不是經常做的事:
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<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
你好,先生,請檢查我的答案,這是非常有序和甜蜜:) –
@ParthSolanki不錯;你不需要像進口和類的東西;) –
好吧,先生,謝謝你的建議,我會更新我的答案。 –
二維數組是固定長度的。你不能追加元素給他們。最好的選擇(與二維數組保持一致)是創建一個更大尺寸的新數組,以保存當前值和新值。然後將所有值添加到它。 –
Yash Capoor是對的。如果這種方法太麻煩了,你可能會更好地切換到'ArrayList'。 –
Daneel
@uksz請檢查我的答案 –