//实现了Compareble的学生类,并重写了compareTo方法。
public class Student implements Comparable<Student> {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public int hashCode(){
return this.name.hashCode()+this.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(Student student){
return this.name+"==="+this.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 compareTo(Student student) {
int num = new Integer(this.age).compareTo(student.age);
if (num == 0){
return this.name.compareTo(student.name);
}
return num;
}
}
public class HashSetDemo04 {
public static void main(String args[]){
Map<Student,String> map = new HashMap<Student,String>();
map.put(new Student("win12",12), "shanghai");
map.put(new Student("win11",11), "shenzhen");
map.put(new Student("win14",14), "wuhan");
map.put(new Student("win16",16), "nanchang");
Set<Student> key = map.keySet();
Iterator<Student> it = key.iterator();
while(it.hasNext()){
Student key2 = it.next();
System.out.println(key2.toString()+"-===="+map.get(key2));
}
}
}
实际打印结果为:
com.heima.collection.Map.Student@6be4c95-====shanghai
com.heima.collection.Map.Student@6be4d21-====nanchang
com.heima.collection.Map.Student@6be4c72-====shenzhen
com.heima.collection.Map.Student@6be4cdb-====wuhan
我想要的打印结果是输出类对象而不是hash字节码!!! |