有可能这样做吗?我希望能够为用户提供将另一个元素添加到数组的选项,该数组设置为长度为5并且已经填充。我相信这会将数组长度增加1?另外,请知道我知道如何在ArrayList中执行此操作。我希望能够在正常的数组中执行此操作。
我听说Arrays.copyof()
可以帮助我做到这一点,但我不明白怎么做?
答案 0 :(得分:1)
如果数组已填满,则无法再添加一个元素。
您需要构建一个更大的数组并将旧数组中的值复制到新数组中。这就是Arrays.copyOf
派上用场的地方。
出于性能原因,每次重建新阵列时最好添加1个以上的空单元格。但基本上,您将构建自己的ArrayList
实现。
答案 1 :(得分:0)
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
如果你要添加很多元素,而不是每次都让数组大一个元素,那么每当数组变满时,你应该考虑将数组的大小加倍。这样可以节省您每次复制所有值的费用。
答案 2 :(得分:0)
在ArrayList中,您只需添加另一个值,而无需执行任何操作。在内部,ArrayList将创建一个新的,更大的数组,将旧数组复制到其中,并将值添加到其中。
如果您想使用数组执行此操作,则需要自己完成此项工作。正如您所想,Arrays.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]
答案 3 :(得分:0)
List<Object> name = ArrayList<Object>();
name.add(userInput);
它更好,更有效率。还有方便的使用方法(特别是add(Object),indexOf(Object),get(Object),remove(Object))。