求教问题
编写学生类 Student,提供如下字段:age(年龄),name(姓名)。为学生类提供带参数的构造方法用于初始化这两个字段。编写测试类,创建两个学生类的对象stu1和stu2,测试是否stu1==stu2,或者是否stu1。squals(stu2)相等?
------解决方案--------------------package com.fzw.test;
public class Student {
private int age;
private String name;
public Student(int age, String name) {
super();
this.age = age;
this.name = name;
}
public static void main(String[] args) {
try {
testStudent();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void testStudent() throws Exception {
Student stu1=new Student(1, "胡总");
Student stu2=new Student(2, "温总");
System.out.println("对两学生进行=判断"+stu1.campareStudent(stu1, stu2, 1));
System.out.println("对两学生进行equals判断"+stu2.campareStudent(stu1, stu2, 2));
}
@SuppressWarnings("unused")
private boolean campareStudent(Object stu1,Object stu2,int i) {
return (i==1?stu1==stu2:stu1.equals(stu2));
// TODO Auto-generated method stub
}
}
------解决方案--------------------Student类
Java code
public class Student {
private String name;
private int age;
public Student(){}
public Student(String name, int age) {
super();
this.name = name;
this.age = 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;
}
@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;
Student other = (Student) 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;
}
}