| 本帖最后由 HM许涛 于 2013-4-25 22:29 编辑 
 学习黑马毕向东老师基础视频中案例,在Map练习中需要用到定义的Student类。在注释掉最后三个方法的情况下,编译通过,运行结果如下:
 输出完成 (耗时 0 秒) - 正常终止
 将最后的toString注释去掉后,运行正常了。个人理解是第一个没有toString方法,返回了内存的位置。有了以后,返回了具体值。不知道对不对。
 
 有没哪位大神能说一下toString有和没有的实现原理?
 
 import java.util.*;
 class Noname1
 {
 public static void main(String[]args)
 {
 TreeMap<Student,String>tm=new TreeMap<Student,String>();
 tm.put(new Student("lisi1",23),"beij");
 tm.put(new Student("lisi2",22),"nanij");
 tm.put(new Student("lisi3",25),"hj");
 tm.put(new Student("lisi4",26),"sij");
 
 Set<Map.Entry<Student,String>>entrySet=tm.entrySet();
 Iterator<Map.Entry<Student,String>>it=entrySet.iterator();
 while(it.hasNext())
 {
 Map.Entry<Student,String>me=it.next();
 Student stu=me.getKey();
 String addr=me.getValue();
 System.out.println(stu+"::::"+addr);
 }
 }
 }
 class Student implements Comparable<Student>
 {
 public String name;
 public int age;
 Student(String name,int age)
 {
 this.name=name;
 this.age=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;
 }
 public int hashCode()
 {
 return name.hashCode()+age*23;
 }
 public boolean equals(Object obj)
 {
 if(!(obj instanceof Student))
 throw new ClassCastException("类型不匹配");
 Student s=(Student)obj;
 return this.name.equals(s.name)&&this.age==s.age;
 }
 /*public String getName()
 {
 return name;
 }
 public int getAge()
 {
 return age;
 }
 public String toString()
 {
 return name+":::::"+age;
 }*/
 }
 
 
 |