| 
 
| 本帖最后由 满兴旺 于 2014-4-17 22:44 编辑 
 /*
 每一个学生都有对应的归属地。
 学生Student 地址String
 */
 
 import java.util.*;
 
 class Student implements Comparable<Student>
 {
 private String name;
 private int age;
 Student(String name,int age)
 {
 this.name=name;
 this.age=age;
 }
 public String getName()
 {
 return name;
 }
 public int getAge()
 {
 return age;
 }
 
 public String toString()
 {
 return name+"..."+age;
 }
 /*********************/
 public int hashCode()
 {
 return name.hashCode()+age*34;
 }
 
 public boolean equals(Object obj)
 {
 if(!(obj instanceof Student))
 throw new RuntimeException("类型不匹配");
 else{
 Student stu=(Student)obj;
 
 return (this.name==stu.getName() && this.age==stu.age);//age不是私有的吗?应该用getAge()方法来访问啊。。。
 为什么这里可以直接访问????
 }
 }
 /**************************/
 public int compareTo(Student stu)
 {
 int num=new Integer(this.age).compareTo(stu.getAge());
 if(num==0)
 {
 return this.name.compareTo(stu.getName());
 }
 return num;
 }
 }
 
 class MapTest
 {
 public static void sop(Object obj)
 {
 System.out.println(obj);
 }
 
 public static void main(String[] args)
 {
 HashMap<Student,String> hm=new HashMap<Student,String>();
 
 hm.put(new Student("lisi1",21),"北京");
 hm.put(new Student("lisi1",21),"保定");
 hm.put(new Student("lisi2",22),"北京");
 hm.put(new Student("lisi3",22),"北京");
 hm.put(new Student("lisi4",23),"北京");
 
 //第一种取出
 sop("第一种取出方式");
 Set<Student> keySet=hm.keySet();
 
 Iterator<Student> it=keySet.iterator();
 
 while(it.hasNext())
 {
 Student stu=it.next();
 String address=hm.get(stu);
 
 sop(stu.toString()+"..."+address);
 }
 }
 }
 
 问题在代码中 return (this.name==stu.getName() && this.age==stu.age);
 age不是私有的吗?应该用getAge()方法来访问啊。。。
 为什么这里可以直接访问????
 | 
 |