Home > Java > javaTutorial > body text

What are the methods to insert elements into java array?

王林
Release: 2023-05-16 09:10:06
forward
6947 people have browsed it

1. Use the insertElement () method to insert elements into the array

import java.util.Arrays;
public class Test{
     
     
     
    public static void main(String args[]) throws Exception {
     
     
     
        int array[] = {
     
     
      2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
        Arrays.sort(array);
        int index = Arrays.binarySearch(array, 1);
        System.out.println("元素 1 所在位置(负数为不存在):"
                + index);
        int newIndex = -index - 1;
        array = insertElement(array, 1, newIndex);
        System.out.println("添加元素1后:"+Arrays.toString(array));
    }
 
    private static int[] insertElement(int original[],
                                       int element, int index) {
     
     
     
        int length = original.length;
        int destination[] = new int[length + 1];
        System.arraycopy(original, 0, destination, 0, index);
        destination[index] = element;
        System.arraycopy(original, index, destination, index
                + 1, length - index);
        return destination;
    }
}
/* 输出结果:
元素 1 所在位置(负数为不存在):-6
添加元素1:[-9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8]
 */
Copy after login

2. Convert the array into a set, add elements to the set, and then convert the set Convert to an array

import java.util.*;
public class Test{
     
     
     
    public static void main(String[] args) {
     
     
     
        String[] arr = {
     
     
     "ID", "姓名"};
        // 将数组转化为集合 1
        List<String> list1 = Arrays.asList(arr);
        List<String> list2 = new ArrayList<>();
        // 定义集合 2 、并向其中添加元素: 性别
        list2.add("性别");
        List<String> List = new ArrayList<String>();
        // 定义新集合、将集合1、2中的元素添加到新集合
        List.addAll(list1);
        List.addAll(list2);
        // 将新集合转化回新数组
        String[] newArr = List.toArray(new String[List.size()]);
        System.out.println(Arrays.toString(newArr));
    }
}
/* 输出结果: [ID, 姓名, 性别]  */
Copy after login

3. Create a new array. The size of the new array is 1, the size of the old array. Copy the elements in the old array into the new one. Array, and add the elements to be added to the new array.

The above is the detailed content of What are the methods to insert elements into java array?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template