Map:拥有将对象映射到另一对象的能力,这可以帮助我们解决很多编程问题。
标准Java类库包含了这几种基本实现:HashMap,Linked
HashMap,TreeMap,ConcurrentHashMap等。map通过将键值绑定,能方便我们通过键查询值,它的键组可以视为一个Set集合,因此不含重复的元素。
-
import java.util.*;
-
-
public class Main {
-
public static void main(String[] args) {
-
Map<Student, Integer> map = new TreeMap<Student, Integer>();
-
Student[] stu = new Student[5];
-
stu[0]=new Student("wang",70);
-
stu[1]=new Student("li", 80);
-
stu[2]=new Student("zhang",70);
-
stu[3]=new Student("zhao", 90);
-
stu[4]=new Student("sun", 90);
-
for(int i=0;i<5;i++){
-
map.put(stu[i], i);
-
}
-
Set<Student> set = map.keySet();
-
System.out.println(map);
-
System.out.println(set);
-
}
-
}
-
-
class Student implements Comparable<Student>{
-
String name;
-
int score;
-
@Override
-
public int compareTo(Student o) {
-
// TODO Auto-generated method stub
-
if(this.equals(o))
-
return this.score-o.score;
-
else
-
return this.score>=o.score?1:-1;
-
}
-
-
public Student(String name,int score){
-
this.name=name;
-
this.score=score;
-
}
-
-
public String toString(){
-
return name+" "+score;
-
}
-
-
public boolean equals(Object o){
-
return o instanceof Student && this.name==((Student)o).name && this.score==((Student)o).score;
-
}
-
-
/*public int hashCode(){
-
return score;
-
}*/
-
}
阅读(1436) | 评论(0) | 转发(0) |