java数组扩容
本文作者:合肥工业大学 管理学院 钱洋 email:1563178220@qq.com 内容可能有不到之处,欢迎交流。
未经本人允许禁止转载。
说明
在编写一些非参学习算法时,例如DP和HDP,经常会遇到生成新簇的情形,这种情况下,数组的空间就不够用了,需要对原来的数组进行扩容。
例如:
int K=10;
int[] tables = new int[K]; //可以看出该数组最多可存储10个元素
for (int i = 0; i <K; i++) {
tables [i] = i; //数组赋值
}
如何让上面已经赋值的数组扩展到可存储11个元素、12个元素等等呢?
针对二维数组,如下:
int C =10;
int[][] tablesNum = new int[C][10];
for (int i = 0; i < tablesNum.length; i++) { for (int j = 0; j < tablesNum[i].length; j++) { tablesNum[i][j] = i*j; //二维数组赋值 } }
可以看出该二维数组最多存储100个元素,如何让其存储更多的元素呢?
解决程序
如下我提供了针对一维数组和二维数组扩容的方法,主要使用的是:System.arraycopy()方法。
//将数组放大,确保不越界
public static int[] ensureCapacity(int[] arr,int i) {
int length = arr.length;
int[] arr2 = new int[length+i];
System.arraycopy(arr, 0, arr2, 0, length);
return arr2;
}
//将数组放大,确保不越界
public static int[][] ensureCapacity(int[][] array,int i,int j) {
int[][] arr = new int[array.length +i][array[0].length +j];
//扩展
for(int c = 0; c< array.length; c++) {
//数组拷贝
System.arraycopy(array[c], 0, arr[c], 0, array[c].length);
}
return arr;
}
算例程序
import java.util.List;
public class Test {
public static void main(String[] args) {
int K=10;
int[] tables = new int[K];
for (int i = 0; i <K; i++) {
tables [i] = i;
}
tables = ensureCapacity(tables,3);
tables[K]=10;
for (int i = 0; i < tables.length; i++) {
System.out.print(tables[i]+"\t");
}
System.out.println();
System.out.println("======================");
int C =10;
int[][] tablesNum = new int[C][10];
for (int i = 0; i < tablesNum.length; i++) {
for (int j = 0; j < tablesNum[i].length; j++) {
tablesNum[i][j] = i*j;
}
}
tablesNum = ensureCapacity(tablesNum,2,2);
for (int i = 0; i < tablesNum.length; i++) {
for (int j = 0; j < tablesNum[i].length; j++) {
System.out.print(tablesNum[i][j]+"\t");
}
System.out.println();
}
}
//将数组放大,确保不越界
public static int[] ensureCapacity(int[] arr,int i) {
int length = arr.length;
int[] arr2 = new int[length+i];
System.arraycopy(arr, 0, arr2, 0, length);
return arr2;
}
public static int[][] ensureCapacity(int[][] array,int i,int j) {
int[][] arr = new int[array.length +i][array[0].length +j]; //扩展
for(int c = 0; c< array.length; c++) {
System.arraycopy(array[c], 0, arr[c], 0, array[c].length); //数组拷贝
}
return arr;
}
}
还没有评论,来说两句吧...