java - Java 是否有通用的相等性测试也能处理空值?

标签 java

Java 标准库中是否有任何地方具有类似这样的静态相等函数?

public static <T> boolean equals(T a, T b)
{
    if (a == null)
        return b == null;
    else if (b == null)
        return false;
    else
        return a.equals(b);
}

我刚刚在新项目 Util 类中实现了无数次。似乎难以置信它不会作为标准库函数发布...

最佳答案

在 JDK 7 中有 Objects#equals() .来自 Javadoc:

Returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals method of the first argument.

除了 Apache Commons Lang 中已经提到的函数之外,Google Guava 中还有一个函数,Objects#equal() :

关于java - Java 是否有通用的相等性测试也能处理空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17244537/

相关文章:

java - jsoup 获取带有类的 div 元素

java - 如何在 TextView 中获取具有特定符号的特定行

java - 在 Quarkus 中重定向到 https

Java:使用过滤器(用户已登录/用户未登录)

java - RemoteWebDriver 无法转换为 org.openqa.selenium.TakesScreenshot (Java)

java - com.microsoft.sqlserver.jdbc.SQLServerException : The result set has no current row

java - 使用java 8流根据某些标准读入1个文件并写出3个文件

Java SWT 按钮图像不刷新

java - 从文件中读取属性并在ant中分配给不同的名称?

java - 文件在对象创建时自行清除