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

前端之家收集整理的这篇文章主要介绍了JSONArray中的put(int index, X value)深入前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
JSONArray中的put(int index,X value)
今天有意间看了一下put(int index,X value),发现了原来这个并不是那么简单,也就是说put(1,"First")和put(1000,"One Thousand")是代价不一样的。
深入代码一下:
  1. public JSONArray put(int index,Object value) throws JSONException {
  2. if (value instanceof Number) {
  3. // deviate from the original by checking all Numbers,not just floats & doubles
  4. JSON.checkDouble(((Number) value).doubleValue());
  5. }
  6. while (values.size() <= index) {
  7. values.add(null);
  8. }
  9. values.set(index,value);
  10. return this;
  11. }

其中最重要的是这句话
  1. while (values.size() <= index) {
  2. values.add(null);
  3. }

其中values是一个ArrayList
  1. public JSONArray() {
  2. values = new ArrayList<Object>();
  3. }

所以put(1,"One Thousand")是代价不一样的。
但是为什么会增加这么多key-value呢(如其中的2,3。。。999)原因就是values是ArrayList,下面是ArrayList.set(index,value)方法
  1. @Override public E set(int index,E object) {
  2. Object[] a = array;
  3. if (index >= size) {
  4. throwIndexOutOfBoundsException(index,size);
  5. }
  6. @SuppressWarnings("unchecked") E result = (E) a[index];
  7. a[index] = object;
  8. return result;
  9.  
所以现在可以知道,上面疑问的原因了。这就是ArrayList的数组属性。 以上是今天工作遇到的一个小问题,整理一下。

猜你在找的Json相关文章