Null进入阵列

时间:2014-06-30 06:50:41

标签: java multithreading

我想知道null如何进入这个memcached对象数组。

Object[] value = (Object[]) SuperCache.getInstance()
                    .get(key);
Object data = cacheStore.getValue();
Object[] newValue;
    if (data != null) {
        if (value == null || value.length <= 0) {
            newValue = new Object[1];
            newValue[0] = data;
            log.info("CacheThread : no value found for k"
                    + key + ", adding a new value now v"
                    + data);
        } else {
            newValue = new Object[value.length + 1];
            newValue[0] = data;
            System.arraycopy(value, 0, newValue, 1,
                    value.length);
            for (int i = 0; i < newValue.length; i++) {
----->          if (newValue[i] == null)
                    log.error("null getting into cache here, for key "
                            + key);
            }
        }
        cacheData(key, newValue, cacheStore.getExpiry());
        log.info("CacheThread " + this.toString()
            + " Lenght of Array" + newValue.length
            + "for k" + key + "v" + newValue);
    }

在上面指出的那一行,我正在检查newValue数组是否为null。但是因为你注意到我正在通过迭代构建数组。

为什么我在这里得到空?

2 个答案:

答案 0 :(得分:1)

数组value可以包含null个值。你没有在任何地方检查它们。

只需在第二行打印它们即可验证:

for (int i = 0; i < value.length; i++) {
      if (value[i] == null)
            log.error("null getting into cache here, at index" + i);

答案 1 :(得分:0)

else {
            newValue = new Object[value.length + 1];
            newValue[0] = data; // this part is assigning only index 0 to an object, you're looping to < newValue.length index
            System.arraycopy(value, 0, newValue, 1,
                    value.length);
            for (int i = 0; i < newValue.length; i++) {
                if (newValue[i] == null) // when i = 1 onwards, it will be null as they are not assigned yet
                    log.error("null getting into cache here, for key "
                            + key);
            }
        }

似乎问题在于newValue [0] = data;

仅将索引0分配给data变量对象。但是你的循环循环到newValue数组的大小。因此,索引1以后将为NULL。

else {
            newValue = new Object[value.length + 1];
            System.arraycopy(value, 0, newValue, 1,
                    value.length);
            for (int i = 0; i < newValue.length; i++) {
               newValue[i] = data;
               if (newValue[i] == null)
                    log.error("null getting into cache here, for key "
                            + key);
            }

这可能就是你所需要的。