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;
}
/*因爲hashset存儲時需要調用hashCode,equals方法,
* hashcode通常需要被複寫,默認的hashCode方法是根據地址值進行比較的*/
public int hashCode(){
return name.hashCode()+age*34;
}
public boolean equals(Object obj){
if(!(obj instanceof Student)){
return false;
}
Student s = (Student)obj;
return this.name.equals(s.name)&&this.age==s.age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public String toString(){
return name+":"+age;
}
@Override
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 MapDemo {
public static void main(String[] args) {
HashMap<Student,String> hm=new HashMap<Student,String>();
hm.put(new Student("zhang", 18), "zunan");
hm.put(new Student("zhang", 18), "hunan");
hm.put(new Student("wang", 19), "wuhan");
hm.put(new Student("li", 20), "beijing");
//第一種取出方式 keySet
Set<Student> keySet = hm.keySet();
Iterator<Student> it=keySet.iterator();
while(it.hasNext()){
Student st = it.next();
String addr = hm.get(st);
System.out.println(st+" "+addr);
}
//第二種取出方式 entrySet
Set<Map.Entry<Student,String>> entrySet = hm.entrySet();
Iterator<Map.Entry<Student,String>> ite = entrySet.iterator();
while(ite.hasNext()){
Map.Entry<Student,String> me = ite.next();
Student student = me.getKey();
String addr = me.getValue();
System.out.println(student+" "+addr);
}
}
}
Map使用的小練習
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.