1
Java 中 null > 0 为什么要报错,怎么用语法糖或者 JDK 封装的方法避免
source link: https://www.v2ex.com/t/941309
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
if (a > 0) { }
if (Objects.compare(a, 0L, Long::compareTo) > 0) { }
Exception in thread "main" java.lang.NullPointerException
上面这样写如果 a 是 null 就都会报错
一般写法是这样可以避免
if (a != null && a > 0) { }
···
但我实在不想每次遇到都写一遍判空逻辑
null 和 0 本来就不相等,为啥还要报错
我想找一个 JDK 封装的方法去解决,但没找到
第 1 条附言 · 7 小时 14 分钟前
这种就是jdk自己封装的
Strings.isBlank()
public static boolean isBlank(final String s) {
if (s == null || s.isEmpty()) {
return true;
}
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!Character.isWhitespace(c)) {
return false;
}
}
return true;
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK