gpt4 book ai didi

java - 在单个函数中重构 java,检查不同数据类型的 null 值

转载 作者:行者123 更新时间:2023-12-02 04:54:49 25 4
gpt4 key购买 nike

我有很多类似下面的语句

boolean isIdEqual = (retrievedEdition.getId() == null && edition.getId() == null) || (retrievedEdition.getId() !=null && edition.getId() != null && retrievedEdition.getId().equals(edition.getId())); 

用于单元测试。我正在检查几种数据类型的 null 值,例如 long、int、Integer、String。我想要一个可以检查两种数据类型并缩短上述语句并重构该代码的函数。

最佳答案

Objects.equals(Object, Object) 不适合您吗?

Objects.equals(retrievedEdition.getId(), edition.getId());

来自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.

Objects 类是在 Java 7 中引入的,如果您使用的是早期版本,则实现如下所示:

/**
* Returns {@code true} if the arguments are equal to each other
* and {@code false} otherwise.
* Consequently, if both arguments are {@code null}, {@code true}
* is returned and if exactly one argument is {@code null}, {@code
* false} is returned. Otherwise, equality is determined by using
* the {@link Object#equals equals} method of the first
* argument.
*
* @param a an object
* @param b an object to be compared with {@code a} for equality
* @return {@code true} if the arguments are equal to each other
* and {@code false} otherwise
* @see Object#equals(Object)
*/
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}

关于java - 在单个函数中重构 java,检查不同数据类型的 null 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28895075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com