0
点赞
收藏
分享

微信扫一扫

TreeMap使用自定义Comparator

刘员外__ 2022-11-04 阅读 82

public class MapT {


public static void main(String[] args) {

TreeMap<Student,String> tm=new TreeMap<Student,String>(new StuNameComparator());


tm.put(new Student("黎明", 21),"北京");

tm.put(new Student("小红", 20),"上海");

tm.put(new Student("小明", 25),"武汉");

tm.put(new Student("小兰", 20),"南京");

tm.put(new Student("黎明", 21),"南京");


Set<Map.Entry<Student,String>> entrySet=tm.entrySet();

Iterator<Map.Entry<Student,String>> itor=entrySet.iterator();

while(itor.hasNext()){


Map.Entry<Student,String> me= itor.next();


Student stu=me.getKey();


String addr=me.getValue();


System.out.println(stu.toString()+" "+addr);

}

}
}

//************************************************************
import java.util.Comparator;


public class StuNameComparator implements Comparator<Student>{


@Override
public int compare(Student s1, Student s2) {
// TODO Auto-generated method stub
int num=s1.getName().compareTo(s2.getName());
if(num==0){
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
}

return num;
}

}//*************************************************************
public class Student implements Comparable<Student>{
private String name;
private int age;
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;
}


public int hashCode(){
return name.hashCode()+age*34;
}
public boolean equals(Object obj){
if(!(obj instanceof Student)){
throw new ClassCastException("类型不匹配");
}
Student s=(Student)obj;
return this.name.equals(s.name)&&this.age==s.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;
}


}

举报

相关推荐

自定义QDialog使用详解

vue自定义指令使用

0 条评论