請問為啥輸出的學生對象的 姓名 年齡都是空值
/*
?* 學生屬性:姓名,年齡
?* 注意:姓名和年齡相同的視為同意學生
?*?
?*?
?* 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
2018-07-21