您的位置:首页 > 产品设计 > UI/UE

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

2013-06-26 19:27 411 查看
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的数组属性。

以上是今天工作遇到的一个小问题,整理一下。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息