在Java中,创建可变数组可以通过以下几种方式:
1. 使用`ArrayList`类:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList
numbers = 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) {
Vector
fruits = 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`作为替代。此外,可变参数只能作为方法的最后一个参数,并且不能作为方法的返回值
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/95596.html