今天有意间看了一下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)方法
所以现在可以知道,上面疑问的原因了。这就是ArrayList的数组属性。 以上是今天工作遇到的一个小问题,整理一下。
- @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;