Chinaunix首页 | 论坛 | 博客
  • 博客访问: 152791
  • 博文数量: 47
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 405
  • 用 户 组: 普通用户
  • 注册时间: 2014-11-23 14:38
文章分类

全部博文(47)

文章存档

2017年(7)

2016年(4)

2015年(19)

2014年(17)

我的朋友

分类: Java

2015-09-11 15:19:11

Map:拥有将对象映射到另一对象的能力,这可以帮助我们解决很多编程问题。
标准Java类库包含了这几种基本实现:HashMap,LinkedHashMap,TreeMap,ConcurrentHashMap等。map通过将键值绑定,能方便我们通过键查询值,它的键组可以视为一个Set集合,因此不含重复的元素。

点击(此处)折叠或打开

  1. import java.util.*;

  2. public class Main {
  3.     public static void main(String[] args) {
  4.         Map<Student, Integer> map = new TreeMap<Student, Integer>();
  5.         Student[] stu = new Student[5];
  6.         stu[0]=new Student("wang",70);
  7.         stu[1]=new Student("li", 80);
  8.         stu[2]=new Student("zhang",70);
  9.         stu[3]=new Student("zhao", 90);
  10.         stu[4]=new Student("sun", 90);
  11.         for(int i=0;i<5;i++){
  12.             map.put(stu[i], i);
  13.         }
  14.         Set<Student> set = map.keySet();
  15.         System.out.println(map);
  16.         System.out.println(set);
  17.     }
  18. }

  19. class Student implements Comparable<Student>{
  20.     String name;
  21.     int score;
  22.     @Override
  23.     public int compareTo(Student o) {
  24.         // TODO Auto-generated method stub
  25.         if(this.equals(o))
  26.             return this.score-o.score;
  27.         else
  28.             return this.score>=o.score?1:-1;
  29.     }
  30.     
  31.     public Student(String name,int score){
  32.         this.name=name;
  33.         this.score=score;
  34.     }
  35.     
  36.     public String toString(){
  37.         return name+" "+score;
  38.     }
  39.     
  40.     public boolean equals(Object o){
  41.         return o instanceof Student && this.name==((Student)o).name && this.score==((Student)o).score;
  42.     }
  43.     
  44.     /*public int hashCode(){
  45.         return score;
  46.     }*/
  47. }


阅读(1368) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~