在 JDK 的 HashMap 源码中有这么一个方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| static Class<?> comparableClassFor(Object x) { if (x instanceof Comparable) { Class<?> c; Type[] ts, as; Type t; ParameterizedType p; if ((c = x.getClass()) == String.class) // bypass checks return c; if ((ts = c.getGenericInterfaces()) != null) { for (int i = 0; i < ts.length; ++i) { if (((t = ts[i]) instanceof ParameterizedType) && ((p = (ParameterizedType)t).getRawType() == Comparable.class) && (as = p.getActualTypeArguments()) != null && as.length == 1 && as[0] == c) return c; } } } return null; }
|
1 2 3
|
if (x instanceof Comparable) {
|
做个小 demo
1 2 3 4 5
| public static void main(String[] args) { Object o = null; System.out.println(o instanceof Object); }
|
根据返回的结果,说明了,如果是对象为 null 则 instanceof 的结果也是 false,也就是说,instanceof Object 在一定程度上的能够代替 o == null 的判断。
性能问题就要另行进行评估了。