Guava 简明教程
Guava - Objects Class
Objects 类提供了适用于所有对象的辅助函数,例如 equals、hashCode 等。
Class Declaration
以下是 com.google.common.base.Objects 类的声明 -
@GwtCompatible
public final class Objects
extends Object
Class Methods
Sr.No |
Method & Description |
1 |
static boolean equal(Object a, Object b) 确定两个可能为 null 的对象是否相等。 |
2 |
static <T> T firstNonNull(T first, T second) 已弃用。改为使用 MoreObjects.firstNonNull(T, T)。此方法计划在 2016 年 6 月移除。 |
3 |
static int hashCode(Object…​ objects) 为多个值生成哈希码。 |
4 |
static Objects.ToStringHelper toStringHelper(Class<?> clazz) 已弃用。请改用 MoreObjects.toStringHelper(Class)。此方法计划在 2016 年 6 月移除。 |
5 |
static Objects.ToStringHelper toStringHelper(Object self) 已弃用。请改用 MoreObjects.toStringHelper(Object)。此方法计划在 2016 年 6 月移除。 |
6 |
static Objects.ToStringHelper toStringHelper(String className) 已弃用。请改用 MoreObjects.toStringHelper(String)。此方法计划在 2016 年 6 月移除。 |
Example of Objects Class
使用任意你选择的编辑器在 C:/> Guava. 中创建以下 Java 程序
GuavaTester.java
import com.google.common.base.Objects;
public class GuavaTester {
public static void main(String args[]) {
Student s1 = new Student("Mahesh", "Parashar", 1, "VI");
Student s2 = new Student("Suresh", null, 3, null);
System.out.println(s1.equals(s2));
System.out.println(s1.hashCode());
System.out.println(
Objects.toStringHelper(s1)
.add("Name",s1.getFirstName()+" " + s1.getLastName())
.add("Class", s1.getClassName())
.add("Roll No", s1.getRollNo())
.toString());
}
}
class Student {
private String firstName;
private String lastName;
private int rollNo;
private String className;
public Student(String firstName, String lastName, int rollNo, String className) {
this.firstName = firstName;
this.lastName = lastName;
this.rollNo = rollNo;
this.className = className;
}
@Override
public boolean equals(Object object) {
if(!(object instanceof Student) || object == null) {
return false;
}
Student student = (Student)object;
// no need to handle null here
// Objects.equal("test", "test") == true
// Objects.equal("test", null) == false
// Objects.equal(null, "test") == false
// Objects.equal(null, null) == true
return Objects.equal(firstName, student.firstName) // first name can be null
&& Objects.equal(lastName, student.lastName) // last name can be null
&& Objects.equal(rollNo, student.rollNo)
&& Objects.equal(className, student.className); // class name can be null
}
@Override
public int hashCode() {
//no need to compute hashCode by self
return Objects.hashCode(className,rollNo);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}