比较两个Java对象与检查为null [英] Compare two Java objects with a check for null
本文介绍了比较两个Java对象与检查为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我觉得这样一个新手问这个问题,但是在JDK中有一个方法比较两个对象的相等性,占空的?类似这样:
I feel like such a novice for asking this question, but is there a method in the JDK that compares two objects for equality, accounting for nulls? Something like this:
public static boolean equals(Object o1, Object o2)
{
if (o1 == null)
{
return o2 == null; // Two nulls are considered equal
}
else if (o2 == null)
{
return false;
}
return o1.equals(o2);
}
自己写这个方法似乎很愚蠢,因为我认为它。
It seems silly to write this method myself since I would think that it has to exist already somewhere.
更新:删除了泛型(类型参数),因为在这种情况下没有添加任何值。
Update: Removed the generics (type parameter) since it did not add any value in this case.
推荐答案
Java 7.0添加了一个新的方便的类: Objects
。
Java 7.0 added a new handy class: Objects
.
对于此: Objects.equals(Object a,Object b)
这篇关于比较两个Java对象与检查为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文