TreeMultimap 没有抛出 NullPointerException

TreeMultimap not throwing out NullPointerException

下面的测试示例代码预计会在运行时抛出 NullPointerException 并在控制台中打印一些堆栈跟踪。但它并没有这样做。第 2 行被打印出来,就好像没有发生错误一样。

如果调试执行,您会看到预期的异常 "map.put( k: 3L, new House()); map: Method threw 'java.lang.NullPointerException' exception. Cannot evaluate com.google.common.collect.TreeMultimap.toString()"。但它不会像在运行时异常的情况下那样中断执行。

即使您尝试捕获第 1 行的 NullPointerException,它也不会被捕获。

为什么会这样?

import com.google.common.collect.Multimap;   
import com.google.common.collect.TreeMultimap;
// from com.google.guava version 18.0

public static void main(String args[]) {

    Multimap<Long, House> map = TreeMultimap.create();
    map.put(3L, new House());  //**Line 1** . expected to break the execution.
    System.out.println("done"); // **Line 2**. expected to not get printed.

}

private static class House implements Comparable{

    Integer numberOfRooms_ = null;

    @Override

    public int hashCode() {

        return numberOfRooms_.hashCode(); //NullPointerException generated

    }

    @Override

    public int compareTo(Object o) {

        return 1;

    }

}

jdk 使用 1.7。

According to Javadoc, TreeMultimap is一个:

Implementation of Multimap whose keys and values are ordered by their natural ordering or by supplied comparators. In all cases, this implementation uses Comparable.compareTo(T) or Comparator.compare(T, T) instead of Object.equals(java.lang.Object) (or hashCode - Xaerxess) to determine equivalence of instances.

hashCode 没有被调用,但是 compareTo 被调用,那里没有抛出 NPE。另一方面,如果您使用 HashMultimap,它无法将对象与 hashCode 实现一起抛出 NPE,因为它在幕后使用 equals/hashCode