JAVA中数组的扩容算法

数组:

     1)Java数组对象的大小是固定不变的,数组对象是不可扩容的。

  2)利用数组复制方法能够变通的实现数组扩容。

  3)System.arraycopy()能够复制数组。

  4)Arrays.copyOf()能够简便的创建数组副本。

  5)创建数组副本的同一时候将数组长度添加就变通的实现了数组的扩容。

部分源码:

public class Arrays {

    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;
    }
 
    public static int[] copyOfRange(int[] original, int from, int to) {
        int newLength = to - from;
        if (newLength < 0)
            throw new IllegalArgumentException(from + " > " + to);
        int[] copy = new int[newLength];
        System.arraycopy(original, from, copy, 0,
                         Math.min(original.length - from, newLength));
        return copy;
    }
}

案例:

public class ArrayDemo {

	@Test
	public void test01() {
		int[] ary = { 1, 2, 3 };
		ary = Arrays.copyOf(ary, ary.length + 1);
		System.out.println(ary.length);
		System.out.println(Arrays.toString(ary));
		ary[ary.length - 1] = 4;
		System.out.println(Arrays.toString(ary));// [1, 2, 3, 4]

		// 字符串连接原理
		char[] chs = { '中', '国' };
		chs = Arrays.copyOf(chs, chs.length + 1);
		chs[chs.length - 1] = '北';
		chs = Arrays.copyOf(chs, chs.length + 1);
		chs[chs.length - 1] = '京';
		// 字符数组依照字符串打印
		System.out.println(chs);// 中国北京
	}

}

应用一:

StringBuffer自动扩容的实现原理:



猜你喜欢

转载自blog.csdn.net/ronin_88/article/details/80410379