在Java中,没有内置的可变长数组类型,但可以通过以下几种方法实现动态增长数组:
使用`ArrayList`类
`ArrayList`是Java中的一个集合类,它实现了`List`接口,可以动态地增长和缩小。
import java.util.ArrayList;
public class DynamicArrayExample {
public static void main(String[] args) {
ArrayList
numbers = new ArrayList<>(); numbers.add(10);
numbers.add(20);
numbers.add(30);
System.out.println("数组元素:");
for (int i : numbers) {
System.out.println(i);
}
}
}
使用`System.arraycopy`方法
当需要从现有数组创建一个新的、更大的数组时,可以使用`System.arraycopy`方法。
int[] a = {1, 2, 3, 4};
int[] b = new int[a.length + 2];
System.arraycopy(a, 0, b, 0, a.length);
b[a.length] = 5;
b[a.length + 1] = 6;
System.out.println("扩容后数组a容量为:" + b.length);
for (int i : b) {
System.out.print(i + " ");
}
使用`Arrays.copyOf`方法
`Arrays.copyOf`方法可以创建一个新的数组,其长度为原数组的长度加上指定的增长量。
String[] wordList = new String;
int wordCount = 0;
int arrayGrowth = 50;
while ((strLine = br.readLine()) != null) {
String[] temp = Arrays.copyOf(wordList, wordList.length + arrayGrowth);
System.arraycopy(wordList, 0, temp, 0, wordList.length);
wordList = temp;
// Store the content into an array
Scanner s = new Scanner(strLine);
while (s.hasNext()) {
wordList[wordCount] = s.next();
wordCount++;
}
}
以上方法都可以实现动态增长数组的效果。选择哪种方法取决于具体的应用场景和个人偏好