Object类
类中的方法
hashCode()/toString()/equals()这三个方法时我们今后在做项目时经常要调用的方法,尤其是在编写一个标准的Java类之后,我们常常重写这三个方法,标准的Java类又称为JavaBean, JavaBean的要求: 1.所有成员变量的访问权限:private 2.为每一个成员变量设置一对getter和setter 3.设置一个无参数和全参构造
Person类
package SE01
.n1Object
;
public class Person {
private String name
;
private int age
;
public String
getName() {
return name
;
}
public void setName(String name
) {
this.name
= name
;
}
public int getAge() {
return age
;
}
public void setAge(int age
) {
this.age
= age
;
}
public Person(String name
, int age
) {
super();
this.name
= name
;
this.age
= age
;
}
public Person() {
super();
}
@Override
public String
toString() {
return "Person [name=" + name
+ ", age=" + age
+ "]";
}
@Override
public int hashCode() {
final int prime
= 31;
int result
= 1;
result
= prime
* result
+ age
;
result
= prime
* result
+ ((name
== null
) ? 0 : name
.hashCode());
return result
;
}
@Override
public boolean equals(Object obj
) {
if (this == obj
)
return true;
if (obj
== null
)
return false;
if (getClass() != obj
.getClass())
return false;
Person other
= (Person
) obj
;
if (age
!= other
.age
)
return false;
if (name
== null
) {
if (other
.name
!= null
)
return false;
} else if (!name
.equals(other
.name
))
return false;
return true;
}
}
Test类
public static void main(String
[] args
) {
Person p
=new Person("王五",12);
System
.out
.println(p
.toString());
p
.setName("张三");
p
.setAge(123);
System
.out
.println(p
.toString());
System
.out
.println(p
.getAge());
System
.out
.println(p
.getName());
System
.out
.println(p
.hashCode());
System
.out
.println(p
);
Scanner sc
=new Scanner(System
.in
);
System
.out
.println(sc
);
Random r
=new Random();
System
.out
.println(r
);
ArrayList list
=new ArrayList();
list
.add(1);
list
.add(2);
System
.out
.println(list
);
}
Equals方法
package SE01
.n1Object
;
public class Demo02Equals {
Person p1
=new Person("小明",18);
Person p2
=new Person("小白",19);
Person p3
=new Person("小明",18);
public static void main(String
[] args
) {
Demo02Equals d
=new Demo02Equals();
System
.out
.println(d
.p1
.equals(d
.p2
));
System
.out
.println(d
.p1
.equals(d
.p3
));
Person p1
=new Person("小明",18);
Person p2
=new Person("小白",19);
Person p3
=new Person("小明",18);
System
.out
.println(p1
.hashCode());
System
.out
.println(p3
.hashCode());
System
.out
.println(p1
.equals(p2
));
System
.out
.println(p1
.equals(p3
));
System
.out
.println(p1
==p1
);
System
.out
.println(p1
.equals(p1
));
System
.out
.println(p1
==p3
);
System
.out
.println(p1
.equals(p3
));
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-769.html