实现代码
```
Test.java
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
/**
* 扩展匿名内部类
* 什么叫匿名内部类:
* 没有名字的内部类,用法类似接口实现多态
*
* 案例:手机、电脑类实现充电的功能
*
* 应用场景:
* 当需要实例化多次,调多次重写方法时,选择接口实现多态
* 当只实例化一次去调重写方法时,选择匿名内部类
*
*
*
*/
public class Test {
public static void main(String[] args) {
//比较器:接口实现多态方式
//Map<Student, Integer> map = new TreeMap<>(new MyComparator());
//匿名内部类
Map<Student, Integer> map = new TreeMap<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
//按自己的规则进行排序:先按年龄升序排序;年龄相等,则按姓名降序
if(o1.getAge()==o2.getAge()){
return o2.getName().compareTo(o1.getName());
}
return o1.getAge()-o2.getAge();
}
});
map.put(new Student("zs", 30), 1);
map.put(new Student("zs", 30), 1);
map.put(new Student("ls", 35), 1);
map.put(new Student("ww", 35), 1);
System.out.println(map);
}
}
```
```
package com.qf.c_treemap2;
public class Student {
private String name;
private int 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 String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
}
```