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的數組屬性。
以上是今天工作遇到的一個小問題,整理一下。