Java ArrayList調用構造方法傳入"容量size"不生效,如何初始化List容量size


創建一個ArrayList對象,傳入整型參數

 

@Test
    public void arrayListConstructor(){
        ArrayList<Object> objects = new ArrayList<>(5);
        System.out.println(objects.size());
     // 0 }

 

結果調用size方法,返回結果卻是0。

難道是真的沒生效嗎?

ArrayList對象的size()方法源碼:

/**
     * Returns the number of elements in this list.
     *
     * @return the number of elements in this list
     */
    public int size() {
        return size;
    }

直接返回的是size屬性,繼續看size屬性的定義:

/**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;

是一個整型的變量。

 

再看ArrayList構造方法的源碼:

 

/**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

 

這個構造方法並沒有對"size"屬性做任何操作,雖然不代表其他地方(代理、監聽等)對size進行了處理,但是ArrayList目前沒有這些東西;

因為"size"屬性在構造方法里未被賦值操作,所以當調用"size()"方法時直接返回的"size"屬性,實際上是int變量默認值0

 

只是指定上面構造方法指定的int型參數是容納能力capacity,並非size的大小,list初始化還是沒有一個元素,即size=0

 

那么如何初始化ArrayList容量呢

@Test
    public void appointCapacity(){
        List<Object> src = new ArrayList<>();
        src.add(123);
        src.add("Luo");
        src.add(23.5);
        // 下面一行只是指定lists的容納能力capacity,並非size的大小,list初始化還是沒有一個元素,即size=0
        // List<Object> dest = new ArrayList<>(src.size()));

        List<Object> dest = new ArrayList<>(Arrays.asList(new Object[src.size()]));
        System.out.println(dest.size());
        // 3

        // 注意,源src是第二個參數,而拷貝到鏈表dest是第一個參數
        Collections.copy(dest, src);


        dest.forEach(System.out::println);
    }

上面是對一個數組進行拷貝,指定初始化數組的"size":List<Object> dest = new ArrayList<>(Arrays.asList(new Object[${size}]));

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM