1. 使用`ArrayList`类:
import java.util.ArrayList;public class Main {public static void main(String[] args) {ArrayListnumbers = new ArrayList<>(); numbers.add(10);numbers.add(20);numbers.add(30);System.out.println(numbers); // 输出:[10, 20, 30]}}
2. 使用`Vector`类(虽然`Vector`已经被标记为过时,推荐使用`ArrayList`):
import java.util.Vector;public class Main {public static void main(String[] args) {Vectorfruits = new Vector<>(); fruits.add("Apple");fruits.add("Banana");fruits.add("Orange");fruits.remove("Banana");System.out.println(fruits); // 输出:[Apple, Orange]}}
3. 手动调整数组大小(不推荐,因为需要更多代码):
public class Main {public static void main(String[] args) {int[] array = new int;array = 1;array = 2;array = 3;// 如果需要改变数组长度,可以创建一个新的数组并复制数据int[] newArray = new int[array.length + 5];System.arraycopy(array, 0, newArray, 0, array.length);System.out.println(Arrays.toString(newArray)); // 输出:[1, 2, 3, 0, 0, 0, 0, 0, 0, 0]}}

4. 使用`Arrays.copyOf`方法(适用于基本数据类型数组):
import java.util.Arrays;public class Main {public static void main(String[] args) {int[] original = {1, 2, 3};int[] copy = Arrays.copyOf(original, original.length + 5);System.out.println(Arrays.toString(copy)); // 输出:[1, 2, 3, 0, 0, 0, 0, 0, 0, 0]}}
5. 使用可变参数(varargs),适用于方法参数:
public class Main {public static void printNumbers(int... numbers) {for (int number : numbers) {System.out.println(number);}}public static void main(String[] args) {printNumbers(1, 2, 3, 4, 5);}}
请注意,`Vector`类已经被标记为过时,推荐使用`ArrayList`作为替代。此外,可变参数只能作为方法的最后一个参数,并且不能作为方法的返回值
