JSONArray中的put(int index, X value)深入

來源:互聯網
上載者:User

JSONArray中的put(int index, X value)
今天有意間看了一下put(int index, X value),發現了原來這個並不是那麼簡單,也就是說put(1,"First")和put(1000,"One Thousand")是代價不一樣的。
深入代碼一下:

public JSONArray put(int index, Object value) throws JSONException {        if (value instanceof Number) {            // deviate from the original by checking all Numbers, not just floats & doubles            JSON.checkDouble(((Number) value).doubleValue());        }        while (values.size() <= index) {            values.add(null);        }        values.set(index, value);        return this;}

其中最重要的是這句話 

while (values.size() <= index) {            values.add(null);}

其中values是一個ArrayList

public JSONArray() {        values = new ArrayList<Object>();}

所以put(1,"First")和put(1000,"One Thousand")是代價不一樣的。
但是為什麼會增加這麼多key-value呢(如其中的2,3。。。999)原因就是values是ArrayList,下面是ArrayList.set(index,value)方法

@Override public E set(int index, E object) {        Object[] a = array;        if (index >= size) {            throwIndexOutOfBoundsException(index, size);        }        @SuppressWarnings("unchecked") E result = (E) a[index];        a[index] = object;        return result;

所以現在可以知道,上面疑問的原因了。這就是ArrayList的數組屬性。
以上是今天工作遇到的一個小問題,整理一下。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.