Add String to beginning of String array

前端 未结 9 961
孤独总比滥情好
孤独总比滥情好 2021-01-01 09:44

Is it possible to add a string to beginning of String array without iterating the entire array.

相关标签:
9条回答
  • 2021-01-01 10:18

    try

        String[] a = {"1", "2"};
        String[] a2 = new String[a.length + 1];
        a2[0] = "0";
        System.arraycopy(a, 0, a2, 1, a.length);
    
    0 讨论(0)
  • 2021-01-01 10:21

    You cant...You have to move all the strings coming after it forward to accommodate the new string. If you are directly adding it to 0th index, you will lose the previous element there

    0 讨论(0)
  • 2021-01-01 10:24

    You can do some thing like below

    public class Test {
    
    public static String[] addFirst(String s[], String e) {
        String[] temp = new String[s.length + 1];
        temp[0] = e;
        System.arraycopy(s, 0, temp, 1, s.length);
        return temp;
    }
    
    public static void main(String[] args) {
        String[] s = { "b", "c" };
        s = addFirst(s, "a");
        System.out.println(Arrays.toString(s));
    }
    }
    
    0 讨论(0)
提交回复
热议问题