Objects 类提供适用于所有对象,如 equals
、hashCode
等辅助函数。
类方法说明
官方文档:Objects (Guava: Google Core Libraries for Java 27.0.1-jre API)
方法类型 | 方法描述 |
---|---|
static boolean |
equal(@Nullable Object a, @Nullable Object b) 确定两个可能为null的对象是否相等。 |
static int |
hashCode(Object... objects) 为多个值生成哈希码。 |
测试Demo
java
public class ObjectsTest extends TestCase {
/**
* 确定两个可能是空的对象是否相等。
*/
public void testEqual() {
assertTrue(Objects.equal("a", "a"));
assertTrue(Objects.equal(null, null));
assertFalse(Objects.equal(null, "a"));
assertFalse(Objects.equal("a", null));
String s1 = "foobar";
String s2 = new String(s1);
assertTrue(Objects.equal(s1, s2));
}
public void testHashCode() {
int h1 = Objects.hashCode(1, "two", 3.0);
int h2 = Objects.hashCode(new Integer(1), new String("two"), new Double(3.0));
assertEquals(h1, h2);
System.out.println(h1 == h2); // true
assertTrue(Objects.hashCode(1, 2, null) != Objects.hashCode(1, 2));
assertTrue(Objects.hashCode(1, 2, null) != Objects.hashCode(1, null, 2));
assertTrue(Objects.hashCode(1, null, 2) != Objects.hashCode(1, 2));
assertTrue(Objects.hashCode(1, 2, 3) != Objects.hashCode(3, 2, 1));
assertTrue(Objects.hashCode(1, 2, 3) != Objects.hashCode(2, 3, 1));
}
}