加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:22:33 所属栏目:百科 来源:网络整理
导读: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 J
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,"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的数组属性。 以上是今天工作遇到的一个小问题,整理一下。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读