开发者

NullPointerException, logical shortcut

Here is a simple code snippet and I cannot figure out why does it throw a NullPointerException.

  String lastGroup = "";
  menuTevekenysegekGrouped = new ArrayList<MenuElem>();
  for(MenuElem me : menuA) {
    // double checked that me objects are never null
    // double checked that menuA is never null
    if(me.getGroup() != null && !me.getGroup().equals(lastGroup)) { /* NPE开发者_如何学C!!! */
        lastGroup = me.getGroup();
        MenuElem separ = new MenuElem();
        separ.setCaption(lastGroup);
        separ.setGroupHead(true);
        menuTevekenysegekGrouped.add(separ);
        menuTevekenysegekGrouped.add(me);
    } else {
        menuTevekenysegekGrouped.add(me);
    }
  }

In the first iteration the me.getGroup() returns null. So the first operand of the && is false and second operand should not evaluate according to the JLS, as far as I know. However when I debug the code I get NPE from the marked line. I'd like to know why. (Using JRockit 1.6.0_05 if it matters..)


Are you sure that me itself is not, in fact, null?


From your code (without the stacktrace I have to guess), the following may be null and be the cause: menuA or me or menuTevekenysegekGrouped. And some of the values returned from the methods/or used in the methods may also be null, but it's hard to know...


If me is not null, then the only other object that can be null in the above snippet is menuTevekenysegekGrouped. Add a check before first using it to ensure that it's not null.


The repeated calls to me.getGroup() would bug me enough to pull them out into a local variable:

  String lastGroup = "";
  for(MenuElem me : menuA) {
    String thisGroup = me.getGroup();
    if(thisGroup != null && !thisGroup.equals(lastGroup)) {
        lastGroup = thisGroup;
        MenuElem separ = new MenuElem();
        separ.setCaption(lastGroup);
        separ.setGroupHead(true);
        menuTevekenysegekGrouped.add(separ);
        menuTevekenysegekGrouped.add(me);
    } else {
        menuTevekenysegekGrouped.add(me);
    }
  }

This is only going to fix your problem if in fact me.getGroup() returns different values (sometimes null) on multiple calls with the same me, but it might make it easier to debug, and certainly makes it easier to read.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜