Java 将地点添加到具有有限位置的数组中

huangapple go评论71阅读模式
英文:

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&lt;&gt;() 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&lt;&gt;(initial_size);

huangapple
  • 本文由 发表于 2020年10月20日 22:37:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64447456.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定