要避免重复使用数组推送,可以使用以下解决方法:
List source = new ArrayList<>();
List target = new ArrayList<>();
// 创建一个临时数组
List temp = new ArrayList<>();
temp.add(1);
temp.add(2);
temp.add(3);
// 将临时数组推送到目标数组中
target.addAll(temp);
System.arraycopy()
或者 Arrays.copyOf()
来创建一个新的数组,并将新数组推送到目标数组中。int[] source = {1, 2, 3};
int[] target = new int[source.length + 1];
// 使用 System.arraycopy() 方法复制数组
System.arraycopy(source, 0, target, 0, source.length);
target[source.length] = 4;
int[] source = {1, 2, 3};
int[] target = Arrays.copyOf(source, source.length + 1);
target[source.length] = 4;
无论是哪种方法,都可以确保每次推送时都是一个新的数组,避免了重复使用数组推送的问题。