请问为啥输出的学生对象的 姓名 年龄都是空值
/*
* 学生属性:姓名,年龄
* 注意:姓名和年龄相同的视为同意学生
*
*
* 1, 描述学生
* 2, 定义map容器,将学生作为键,地址作为值,存入
* 3, 获取集合元素
*
*
* */
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class HashMapDemo {
public static void main(String[] args) {
HashMap<student,String> hm=new HashMap<student,String>();
hm.put(new student("zhangsan",21), "nanna2");
hm.put(new student("lisi",26), "nanna1");
hm.put(new student("wangwu",22), "nanna3");
Set<student> set=hm.keySet();
Iterator<student> it=set.iterator();
while (it.hasNext()) {
student stu=it.next();
String adr=hm.get(stu);
System.out.println(stu+" "+adr);
}
}
}
class student implements Comparable<student>{
public int hashcode() {
return name.hashCode()+age*34;
}
public boolean equals(Object obj) {
if(!(obj instanceof student))
throw new ClassCastException("");
student student= (student)obj;
return this.name.equals(student.name)&& this.age==student.age;
}
public String toString() {
return "student [name=" + name + ", 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;
}
private String name;
private int age;
public student() {
}
student(String name,int age){
name=this.name;
age=this.age ;
}
public int compareTo(student s) {
int num=new Integer(this.age).compareTo(new Integer(s.age));
if(num==0)
return this.name.compareTo(s.name);
return num;
}
}
输出结果:
student [name=null, age=0] nanna1
student [name=null, age=0] nanna2
student [name=null, age=0] nanna3