2016-09-23 74 views
1

我有以下几点:如何将元素追加到String [] []?

String[][] content = { 
      {"c","d", "2"}, 
      {"e","f", "3"}, 
      {"g","h", "4"}, 
      {"i","j", "5"}} ; 

我能做些什么,以添加一些元素×3到已经存在的呢?

+1

二维数组是固定长度的。你不能追加元素给他们。最好的选择(与二维数组保持一致)是创建一个更大尺寸的新数组,以保存当前值和新值。然后将所有值添加到它。 –

+0

Yash Capoor是对的。如果这种方法太麻烦了,你可能会更好地切换到'ArrayList '。 – Daneel

+0

@uksz请检查我的答案 –

回答

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]] 
+0

@uksz如果我的回答是有用的,那么请upvote并接受我的答案,提前致谢! –

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<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 
+0

你好,先生,请检查我的答案,这是非常有序和甜蜜:) –

+0

@ParthSolanki不错;你不需要像进口和类的东西;) –

+0

好吧,先生,谢谢你的建议,我会更新我的答案。 –