How to add new elements to an array?

后端 未结 18 1700
误落风尘
误落风尘 2020-11-22 04:55

I have the following code:

String[] where;
where.append(ContactsContract.Contacts.HAS_PHONE_NUMBER + \"=1\");
where.append(ContactsContract.Contacts.IN_VISIB         


        
18条回答
  •  [愿得一人]
    2020-11-22 05:28

    There are many ways to add an element to an array. You can use a temp List to manage the element and then convert it back to Array or you can use the java.util.Arrays.copyOf and combine it with generics for better results.

    This example will show you how:

    public static  T[] append2Array(T[] elements, T element)
    {
        T[] newArray = Arrays.copyOf(elements, elements.length + 1);
        newArray[elements.length] = element;
    
        return newArray;
    }
    

    To use this method you just need to call it like this:

    String[] numbers = new String[]{"one", "two", "three"};
    System.out.println(Arrays.toString(numbers));
    numbers = append2Array(numbers, "four");
    System.out.println(Arrays.toString(numbers));
    

    If you want to merge two array you can modify the previous method like this:

    public static  T[] append2Array(T[] elements, T[] newElements)
    {
        T[] newArray = Arrays.copyOf(elements, elements.length + newElements.length);
        System.arraycopy(newElements, 0, newArray, elements.length, newElements.length);
    
        return newArray;
    }
    

    Now you can call the method like this:

    String[] numbers = new String[]{"one", "two", "three"};
    String[] moreNumbers = new String[]{"four", "five", "six"};
    System.out.println(Arrays.toString(numbers));
    numbers = append2Array(numbers, moreNumbers);
    System.out.println(Arrays.toString(numbers));
    

    As I mentioned, you also may use List objects. However, it will require a little hack to cast it safe like this:

    public static  T[] append2Array(Class clazz, List elements, T element)
    {
        elements.add(element);
        return clazz.cast(elements.toArray());
    }
    

    Now you can call the method like this:

    String[] numbers = new String[]{"one", "two", "three"};
    System.out.println(Arrays.toString(numbers));
    numbers = append2Array(String[].class, Arrays.asList(numbers), "four");
    System.out.println(Arrays.toString(numbers));
    

提交回复
热议问题