有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java添加到已设置/填充的数组

有可能这样做吗?我希望能够为用户提供向数组添加另一个元素的选项,该元素设置为长度5,并且已经填充。我相信这将使数组长度增加1?另外,请知道我知道如何在ArrayList中执行此操作。我希望能够在普通数组中执行此操作

我听说Arrays.copyof()可以帮上忙,但我不明白怎么做


共 (4) 个答案

  1. # 1 楼答案

    在ArrayList中,您只需添加另一个值,而无需执行任何操作。在内部,ArrayList将创建一个新的、更大的数组,将旧数组复制到其中,并向其中添加值

    如果要使用数组执行此操作,则需要自己执行此操作。正如您所想,数组。copyOf()是一种简单的方法。例如:

        int[] a = {1,2,3,4,5};
        System.out.println(a.length); // this will be 5
        System.out.println(Arrays.toString(a)); // this will be [1, 2, 3, 4, 5]
    
        int[] b = Arrays.copyOf(a, 10);
        System.out.println(b.length); // this will be 10, half empty
        System.out.println(Arrays.toString(b)); // this will be [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
    
  2. # 2 楼答案

    import java.util.Arrays;
    
    int[] myArray = new int[]{1,2,3,4,5}; //The array of five
    
    int[] myLongerArray = Arrays.copyOf(myArray, myArray.length + 1); //copy the original array into a larger one
    
    myLongerArray[myLongerArray.length-1] = userInput;  //Add the user input into the end of the new array
    

    <>如果你要添加很多元素,而不是每次使数组一个元素变大,那么当它满时,你应该考虑将数组的大小加倍。这将节省您每次复制所有值的时间

    Here is another example of using copyOf()

  3. # 3 楼答案

    如果数组已填充,则不能再添加一个元素

    您需要构建一个更大的数组,并将值从旧数组复制到新数组。这就是Arrays.copyOf派上用场的地方

    出于性能原因,最好在每次重建新阵列时添加1个以上的空单元。但基本上,您将构建自己的ArrayList实现

  4. # 4 楼答案

    List<Object> name = ArrayList<Object>();
    name.add(userInput);
    

    它更好,更有效。还具有方便的使用方法(尤其是添加(对象)、索引(对象)、获取(对象)、删除(对象))