gpt4 book ai didi

java - 我想使用 System.arraycopy 将新元素插入到数组中。我的代码确实有效,但是还有其他方法可以有效地完成它吗?

转载 作者:行者123 更新时间:2023-11-30 07:04:24 25 4
gpt4 key购买 nike

我在这里阅读了很多关于在数组中插入新元素的帖子,但我的疑虑尚未消除。我做了更多研究并发现了System.arraycopy()方法来做到这一点。但我总觉得效率不高。我还有其他方法可以做到这一点吗?当我尝试 Arrays.asList() 时,将数组转换为数组列表似乎很令人困惑,我无法向其中添加元素。

这是我使用 System.arraycopy() 编写的代码:

import java.util.Arrays;
class example{

public static void main(String[] args) {
int[] array = new int[]{2,3,4,5,6,7};
int[] newarray = new int[7];

int indexvalue = 2;
int num = 8;

System.arraycopy(array, 0, newarray, 0, 2);
System.out.println(newarray[2]=8);
System.arraycopy(array, 2, newarray, 3,4);
System.out.println(Arrays.toString(newarray));
}
}

它给出了这个输出:

run: 8 [2, 3, 8, 4, 5, 6, 7]

BUILD SUCCESSFUL (total time: 0 seconds)

有更好的方法吗?

编辑:我使用数组的原因是因为问题要求我在数组中插入一个新元素。

最佳答案

考虑到您想要动态添加元素,List 可能是正确的数据结构,而不是数组。你可以这样做:

class example{
public static void main(String[] args) {
ArrayList<Integer> array = new ArrayList<>();
array.add(2);
array.add(3);
array.add(4);
array.add(5);
array.add(6);
array.add(7);

int indexvalue = 2;
Integer num = 8;

array.add(indexvalue, num);
}
}

这里是关于我在这里用来插入元素的 add 方法的 javadoc:http://docs.oracle.com/javase/6/docs/api/java/util/List.html#add%28int,%20E%29

由于多种原因,对于您想要做的事情,列表比数组更好,请参阅这篇文章:Array versus List<T>: When to use which?

关于java - 我想使用 System.arraycopy 将新元素插入到数组中。我的代码确实有效,但是还有其他方法可以有效地完成它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40388017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com