• 再练



    import java.util.*;//。
    import java.util.Map.Entry;
     
    class Student implements Comparable <Student>
    /*定义一个Student类覆写hashCode和equals
    方法使其具有比较性继承Comparable接口实现compaeTo方法使其具有一定的排序性*/
    {  
     //定义三个私有成员
     private String name;                                          
     private int num;                                  
     private String addrees;
     Student (String name,int num,String addrees)//构造函数
     {
      this.name=name;
      this.num=num;
      this.addrees=addrees;
     }
     
     public int compareTo(Student s)//实现Comparable接口中的compareTo方法
     {
      int a= this.name.compareTo(s.name);
      if (a==0)
      return new Integer(this.num).compareTo(new Integer(s.num));
      return a;
     }
     public   String getName()
     {
      return name;
     }
     public  int getNum()
     {
      
      return num;
     }
     public  String getAddrees()
     {
      
      return addrees;
     }
     public int hashCode()//覆写hashCode方法
     {
      return name.hashCode()+num*34;
     }
     public boolean equals(Object obj)//覆写equals方法
     {
      if (!(obj instanceof Student))
      {
       throw new ClassCastException("失败");
      }
      Student s=(Student)obj;
      return this.name.equals(s.name)&&this.num==s.num&&this.addrees.equals(s.addrees);
     }
     public String toString()
     {
      return "学号: "+num+" 姓名: "+name+" 地址: "+addrees;
     }
     
    }
    public class MapTest {

     /**
      * @param args
      */
     public static void main(String[] args) {
      // TODO Auto-generated method stub
      HashMap<Student,Integer> map=new HashMap<Student,Integer>();
      map.put(new Student("Tom",001,"Baijing"), 53);
      map.put(new Student("Jam",002,"Baijing"), 87);
      map.put(new Student("Joy",003,"Baijing"), 96);
      map.put(new Student("Pak",004,"Baijing"), 49);
      
      //第一种取出方式 keySet方法
      Set<Student> keyset=map.keySet();
      Iterator it =keyset.iterator();
      while (it.hasNext())
      {
       Student st=(Student) it.next();
       Integer score=map.get(st);
       System.out.println(st+":::"+score);
       
      }
            //第二种取出方式 entrySet方法
      Set<Map.Entry<Student,Integer>> entryset=map.entrySet();
      Iterator<Map.Entry<Student,Integer>> its =entryset.iterator();
      while (its.hasNext())
      {
       Map.Entry<Student,Integer> mm=its.next();
       Student stu= mm.getKey();
       
       Integer sco=mm.getValue();
       System.out.println(stu+" 成绩: "+sco);
      }
      
     }

    }

    
    


  • 相关阅读:
    [android] 获取系统的联系人信息
    [android] 内容观察者
    [nodejs] nodejs开发个人博客(六)数据分页
    [android] 插入一条记录到系统短信应用里
    [android] 短信的备份
    [android] 内容提供者实现
    [android] 内容提供者简介
    [nodejs] nodejs开发个人博客(五)分配数据
    [android] 常用数据适配器SimpleAdapter
    [android] 常用数据适配器ArrayAdapter
  • 原文地址:https://www.cnblogs.com/lixingle/p/3313051.html
Copyright © 2020-2023  润新知