java怎样定义可变长数组

Python018

java怎样定义可变长数组,第1张

JAVA数组初始化后长度就被固定。

使用List来替代数组

用法:

List<String>l = new ArrayList<String>()

l.add("1")

l.add("2")

l.add("3")

System.ou.println(l.szie())

l.add("4")

System.ou.println(l.szie())

结果:

3

4

java中的数组是不可变的,所以要实现可变数组是不可能的了。如果非要改变数组的长度,那么也只能重新开辟一个新的数组然后将长度设定为想要的,然后放弃原来的数组,当然这个放弃的数组,如果没有被引用,它会很快就被GC掉。

java中有一个方法:System.arraycopy

通常我们都使用的是Arrays.copyOf,但你去看API就知道,其实Arrays.copyOf调用的也正是System.arraycopy

public static int[] copyOf(int[] original, int newLength) {

        int[] copy = new int[newLength]

        System.arraycopy(original, 0, copy, 0,

                         Math.min(original.length, newLength))

        return copy

    }