欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java实现延长数组的长度,java数组长度,我们知道数组本身是定长的

来源: javaer 分享于  点击 16357 次 点评:83

java实现延长数组的长度,java数组长度,我们知道数组本身是定长的


我们知道数组本身是定长的,但是ArrayList之类的类底层实现是数组,但是却是变长的,这是如何做到的呢?

其实是在长度需要扩展时,重新建一个数组,然后将原有数组中的元素复制到新数组中来实现的。复制数组是使用System.arraycopy()方法实现的。

/** * Main.java * * @author cn.outofmemory */public class Main {    /**     * Extends the size of an array.     */    public void extendArraySize() {        String[] names = new String[] {"Joe", "Bill", "Mary"};        //Create the extended array        String[] extended = new String[5];        //Add more names to the extended array        extended[3] = "Carl";        extended[4] = "Jane";        //Copy contents from the first names array to the extended array        System.arraycopy(names, 0, extended, 0, names.length);        //Ouput contents of the extended array        for (String str : extended)             System.out.println(str);    }    /**     * Starts the program     *     * @param args the command line arguments     */    public static void main(String[] args) {        new Main().extendArraySize();    }}

上述代码输出如下:

JoeBillMaryCarlJane
相关栏目:

用户点评