标签:
/*Map集合的两种 取出方式
* 1、keySet()
* 2、entrySet()
* */
//定义一个学生类 重写了equals、hashcode三个方法,实现了comparable接口并覆盖comparato方法
package 集合;
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student(){}
public Student(String name,int age){
this.name= name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int hashCode() {
return this.name.hashCode()+age*39;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Student))
throw new ClassCastException("转换类型不匹配");
Student student = (Student)obj;
return this.name.equals(student.getName()) && this.age == student.getAge();
}
public int compareTo(Student stu) {
int num = new Integer(this.age).compareTo(new Integer(stu.getAge()));
if(num == 0)
return this.name.compareTo(stu.getName());
return num;
}
@Override
public String toString() {
return name + age;
}
}
//定义一个HashMAP类
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MapTest1 {
public static void main(String[] args) {
HashMap<Student,String> hm = new HashMap<Student,String>();//不是treeMap调用不到comparato方法
hm.put(new Student("aisi1",22), "上海");
hm.put(new Student("disi2",24), "上海");
hm.put(new Student("cisi4",21), "上海");
hm.put(new Student("aisi3",25), "上海");
//第一种取出方式 keyset
Set<Student> keySet = hm.keySet();
Iterator<Student> it = keySet.iterator();
while(it.hasNext()){
Student stu = it.next();
String address = hm.get(stu);
System.out.println(stu+":"+address);
}
System.out.println("===================");
//第二种取出方式entrySet
Set<Map.Entry<Student, String>> entrySet = hm.entrySet();
Iterator<Map.Entry<Student,String>> it1 = entrySet.iterator();
while(it1.hasNext()){
Map.Entry<Student, String> me = it1.next();
Student stu = me.getKey();
String addr = me.getValue();
System.out.println(stu+":"+addr);
}
}
}
标签:
原文地址:http://www.cnblogs.com/gongxueliang1989/p/5453393.html