- /*
- 每一个学生都有对应的归属地。
- 学生Student,地址String.
- 学生属性:姓名、年龄
- 注意:姓名和年龄相同的视为同一个学生
- 保证学生的唯一性。
- 1、描述学生
- 2、定义map容器。将学生作为键,地址作为值存入。
- 3、获取map集合中的元素。
- */
- 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 this.name;
- }
- public void setName(String name){
- this.name = name;
- }
- public int getAge(){
- return this.age;
- }
- public void setAge(int age){
- this.age = age;
- }
- //覆写toString方法,使有自己的toStrign输出方式
- public String toString(){
- return this.name+":"+this.age;
- }
- //覆写hashCode和equals方法保证Set集合下的HashSet有唯一性
- public int hashCode(){
- return name.hashCode()+age*34;
- }
- 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;
- }
- //实现Comparable接口和覆写compareTo方法保证Set集合下的TreeSet集合有唯一性
- 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 class HashMapTest{
- public static void main(String[] args){
- HashMap<Student,String> hm = new HashMap<Student,String>();
- hm.put(new Student("lisi01",21),"beijing");
- hm.put(new Student("lisi02",22),"shanghai");
- hm.put(new Student("lisi03",23),"nanjing");
- hm.put(new Student("lisi04",24),"wuhan");
-
- //第一种取出方式、keySet
- Set<Student> keySet = hm.keySet();
- Iterator<Student> it = keySet.iterator();
- while(it.hasNext()){
- Student s = it.next();
- String add = hm.get(s);
- sop(s+"..."+add);
- }
- }
- public static void sop(Object obj){
- System.out.println(obj);
- }
- }
复制代码 毕老师讲HashMap有道练习,求大家帮忙找下我错在哪里了
错误:
|