public class Student {
private String name; private int age; public boolean equals(Object o) {
boolean flag = false;
if (o != null) {
if (this == o) {
flag = true;
} else {
if (o instanceof Student) {
Student s = (Student) o;
if (this.name.equals(s.name) && this.age == s.age) {
flag = true;
}
}
}
}
return flag;
} public static void main(String[] args) {
Student s1 = new Student();
s1.name = "kaka";
s1.age = 10;
Student s2 = new Student();
s2.name = "kaka";
s2.age = 10;
System.out.println(s1.equals(s2));
}
}
楼主【skyearthsea】截止到2008-07-14 14:06:03的历史汇总数据(不包括此帖):
发帖的总数量:29 发帖的总分数:480 每贴平均分数:16
回帖的总数量:23 得分贴总数量:2 回帖的得分率:8%
结贴的总数量:28 结贴的总分数:470
无满意结贴数:4 无满意结贴分:60
未结的帖子数:1 未结的总分数:10
结贴的百分比:96.55 % 结分的百分比:97.92 %
无满意结贴率:14.29 % 无满意结分率:12.77 %
值得尊敬
if (o != null) { //如果不为空就XXXXX
.....
} else { //为空的时候就XXXXX
.....
}
问题好多
public class Student
{
private String name; private int age; public boolean equals(Object o)
{
boolean flag = false; if(o != null)
{
if(this == o)
{
flag = true;
}
else if(o instanceof Student)
{
Student s = (Student)o; if(this.name.equals(s.name) && this.age == s.age)
{
flag = true;
}
}
}
return flag;
} public static void main(String[] args)
{
Student s1 = new Student();
s1.name = "kaka";
s1.age = 10;
Student s2 = new Student();
s2.name = "kaka";
s2.age = 10;
System.out.println(s1.equals(s2));
}
}
一看都是规范没学好的,hoho
xxxxxx{
}
xxxxxx{
}
}
代码也有改动好不好楼主的是
if()
{
}
else
{
if()
{
}
}
我改的是
if()
{
}
else if()
{
}
if (obj == this)
return true;
if (!(obj instanceof Student))
return false;
Student s = (Student) obj;
return this.name.equals(s.name) && this.age == s.age;
}
还可以更好一点
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false; if (getClass() != obj.getClass()) return false;
//注意,这里如果用 (obj instanceof Student) 来判断的话,那么Student所有的子类
//的 equals 方法就不能有改变 Student s = (Student) obj; return name.equals(s.name) && age == s.age; }
if(this.name.equals(s.name) && this.age == s.age)
{
flag = true;
}
要是我就先判断一下
如Map添加内容时的equeals。
if (obj == this) return true;
if (obj == null) return false;
if (obj.getClass() != this.getClass()) return false;
Student other = (Student) obj;
return (other.name == null ? this.name == null : other.name.equals(this.name)) &&
(other.age == this.age);
}