黑马程序员技术交流社区
标题:
HashMap不能使用比较器 局限了。。。
[打印本页]
作者:
相见欢
时间:
2014-4-2 23:08
标题:
HashMap不能使用比较器 局限了。。。
import java.util.*;
/*
每一个学生有对应的归属地。
学生Student 地址 String。
学生属性:姓名 年龄
注意:姓名和年龄相同的视为同一个学生
保证学生的唯一性
分析:
1.描述学生
2.定义map集合,将学生作为键,地址作为值存入
3.获取map集合中的元素
*/
class MapTest
{
public static void main(String[] args)
{
HashMap<Student,String> map = new HashMap<Student,String>();//new StuCompare()不可以用比较方器
map.put(new Student("张三",22),"石家庄");
//map.put(new Student("张三",22),"石家庄");
map.put(new Student("李四",23),"邯郸");
map.put(new Student("王五",24),"北京");
//将学生地址的映射关系存入Set集合中,然后输出
Set<Map.Entry<Student,String>> entrySet = map.entrySet();
Iterator<Map.Entry<Student,String>> it = entrySet.iterator();
while (it.hasNext())
{
Map.Entry<Student,String> me = it.next();
Student st = me.getKey();
String addrss = me.getValue();
Sop.sop(st.getName()+st.getAge()+"...."+addrss);
}
}
}
class Student implements Comparator
{
private String name;
private int age;
Student(String name,int age)
{
this.name = name;
this.age = age;
}
//复写hashCode方法
public int hashCode()
{
return name.hashCode()+age*33;
}
//复写equals
public boolean equals(Object obj)
{
if (!(obj instanceof Student))
{
throw new ClassCastException("类型不匹配");
}
Student s = (Student)obj;
return this.name.equals(s.name) && this.age == age;
}
public int compare(Object o1, Object o2)
{
Student st1 = (Student)o1;
Student st2 = (Student)o2;
int num = st1.getName().compareTo(st2.getName());
if (num == 0)
{
return new Integer(st1.getAge()).compareTo(new Integer(st2.getAge()));
}
return num;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setAge(int age)
{
this.age = age;
}
public int getAge()
{
return age;
}
}
class StuCompare implements Comparator//学生对象比较器
{
public int compare(Object o1, Object o2)
{
Student st1 = (Student)o1;
Student st2 = (Student)o2;
int num = st1.getName().compareTo(st2.getName());
if (num == 0)
{
return new Integer(st1.getAge()).compareTo(new Integer(st2.getAge()));
}
return num;
}
}
作者:
相见欢
时间:
2014-4-2 23:11
郁闷了,写完发现不能用,API没看太懂
作者:
疯狂沙漠
时间:
2014-4-3 08:56
从api查看,hashMap的构造方法没有传入比较器的,如果要使用比较器,那就用TreeMap,它的构造方法可以传入比较器,可以使键自动排序
作者:
lazy_xia
时间:
2014-4-3 09:39
HashMap构造方法摘要
HashMap()
构造一个具有默认初始容量 (16) 和默认加载因子 (0.75) 的空 HashMap。
HashMap(int initialCapacity)
构造一个带指定初始容量和默认加载因子 (0.75) 的空 HashMap。
HashMap(int initialCapacity, float loadFactor)
构造一个带指定初始容量和加载因子的空 HashMap。
HashMap(Map<? extends K,? extends V> m)
构造一个映射关系与指定 Map 相同的新 HashMap。
以上的jdk1.6中HashMap的构造方法 没有引用到构造器 所以你传比较器是会报错的
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2