import java.util.*;
class Student implements Comparable
{
private String id;
private String name;
Student(String id,String name)
{
this.id = id;
this.name = name;
}
public String getId()
{
return id;
}
public String getName()
{
return name;
}
public String toString()
{
return id +"::" + name;
}
public int hashCode()
{
return this.id.hashCode() + this.name.hashCode()*30;
}
public boolean equals(Object obj)
{
if(obj instanceof Student)
throw new ClassCastException("类型不符合");
Student s = (Student)obj;
return this.name.equals(s.name) && this.id.equals(s.id);
}
public int compareTo(Student s)
{
if(id.compareTo(s.id)==0)
return this.name.compareTo(s.name);
return this.id.compareTo(s.id);
}
}
class MyCmpt implements Comparator
{
public int compare(String o1,String o2)
{
return 1;
}
}
class MapDemo3
{
public static void demo()
{
TreeMap> czbk = new TreeMap>(new MyCmpt());
List<Student> yure = new ArrayList<Student>();
List<Student> jiuye = new ArrayList<Student>();
czbk.put("yure",yure);
czbk.put("jiuye",jiuye);
yure.add(new Student("01","zhangsan"));
yure.add(new Student("02","lisisan"));
jiuye.add(new Student("01","zhangsansan"));
jiuye.add(new Student("02","zhangxiaosan"));
Set<Map.Entry<String,List<Student>>> e = czbk.entrySet();
for(Iterator<Map.Entry<String,List<Student>>> it = e.iterator(); it.hasNext();)
{
Map.Entry<String,List<Student>> me = it.next();
String st = me.getKey();
List<Student> stu = me.getValue();
System.out.println(st);
getInfos(stu);
}
/*Set<String> s = czbk.keySet();
for(Iterator<String> it = s.iterator();it.hasNext();)
{
String str = it.next();
List<Student> stu = czbk.get(str);
System.out.println(str);
System.out.println(stu);
}*/
}
public static void getInfos(List<Student> list)
{
for(Iterator<Student> it = list.iterator();it.hasNext();)
{
Student s = it.next();
System.out.println(s);
}
}
public static void main(String[] args)
{
demo();
}
}
上面的代码我加入了比较器之后,用entrySet方法用迭代器去遍历键还是指向了值,但是我用keySet方法去遍历,键却指向了空,求解惑?
问题在于
czbk = new TreeMap>(new MyCmpt());//这里设置了比较器
但你的MyCmpt定义只有一种返回值
class MyCmpt implements Comparator
{
public int compare(String o1,String o2)
{
return 1;
}
也就是不管什么key值,都取右节点接着找,直到末尾,最终因为找不到,所以返回null。
这里改成key值相等的时候就返回
public int compare(Object o1,Object o2)
{
return ((String)o1).equals(o2)?0:1;
}
你用的是Set集合,哪里有Key,你的Set是存储了很多个Map
你当然用EntrySet才能迭代取出,对取得的Map对象再keyset才正确
你可能是刚学,代码是copy来的/? 还是自己写的/?
首先,你这段代码还存在语法错误,子类Student实现了Comparable接口了,却没有实现compareTo(Object)方法,我拷贝代码后编译器报错了。
子类重新或者实现接口方法 ,不能修改原来方法的声明的,你虽然也提供了compareTo(Student)但是不是父类声明的方法,所以编译器报错了。