1 .主类 |
package s0224TreeMap; |
import java.util.TreeMap; |
//TreeMap的键必须可排序,要么键是comparable接口实现类的实例,要么给定比较器 |
public class Main { |
public static void main(String [] args){ |
Student a1= new Student( "小明" , 50 ); |
Student a2= new Student( "小张" , 80 ); |
Student a3= new Student( "小往" , 90 ); |
Student a4= new Student( "小会" , 70 ); |
TreeMap<Student,String> map= new TreeMap<Student, String>( //执行比较 |
(Student s1,Student s2)->s1.getScore()-s2.getScore() ); |
|
map.put(a1, "01" ); |
map.put(a2, "01" ); |
map.put(a3, "01" ); |
map.put(a4, "01" ); |
System.out.println(map.keySet()); |
} |
} |
2 .Student类 |
package s0224TreeMap; |
public class Student { |
private String name; |
private int score; |
|
|
public Student(String name, int score) { |
super (); |
this .name = name; |
this .score = score; |
} |
public String toString() |
{ |
return this .name+ " 成绩" + this .score+ "\n" ; |
} |
public String getName() { |
return name; |
} |
public void setName(String name) { |
this .name = name; |
} |
public int getScore() { |
return score; |
} |
public void setScore( int score) { |
this .score = score; |
} |
|
} |