英文:
Java add place to array with a limited number of places
问题
我想在数组"a"的位置上添加元素:
我的代码:
Integer[] a = new Integer[3];
我希望这样做:将"Integer[] a = new Integer[3]" 修改为 "Integer[] a = new Integer[4]"
我尝试过:
a.length += 1;
和:
a[a.length] = a[a.length + 1];
英文:
I want to add place the "a" array:
My code:
Integer[] a = new Integer[3];
I want that: "Integer[] a = new Integer[3]" become to: "Integer[] a = new Integer[4]"
I tried:
a.length += 1;
and:
a[] = a [a.length + 1];
答案1
得分: 1
你无法更改数组的大小。但是,你可以用所需大小的新数组替换旧数组,将旧数组的部分或全部内容复制到新数组中:
Integer[] a = new Integer[3];
a[0] = 1; a[1] = 2; a[2] = 3;
System.out.println(Arrays.toString(a)); // 输出 [1, 2, 3]
a = Arrays.copyOf(a, 4);
a[3] = 4;
System.out.println(Arrays.toString(a)); // 输出 [1, 2, 3, 4]
英文:
You can't change the size of an array. You can, however, replace the old array with a new one of the required size to which some or all of the contents of the old array have been copied:
Integer a = new Integer[3];
a[0] =1; a[1] = 2; a[2] = 3;
System.out.println(Arrays.toString(a)); // Prints [1,2,3]
a = Arrays.copyOf(a, 4);
a[3] = 4;
System.out.println(Arrays.toString(a)); // prints [1,2,3,4]
答案2
得分: 0
Arrays.copy()
是您唯一的解决方案。如建议的ArrayList<>
()也是一种可能的解决方案。
但在幕后,当ArrayList<>
()达到其大小限制时,在处理小堆中的大型列表时,这是一件非常繁琐的事情,并且会耗尽内存。
另外依我之见,如果您了解数据的大小,最好是使用Array
的初始化或初始化ArrayList<>(initial_size)
;
英文:
Arrays.copy()
is your only solution. As suggested ArrayList<>() is also a possible solution.
But under the hood ArrayList<>()
when it reaches its size limit, this is a highly tiresome thing when handling large lists in a small heap, and will run out of memory.
Also in my opinion, if you know about the size of your data. You better go with initialisation of an Array
or initialise ArrayList<>(initial_size)
;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论