實現(xiàn)代碼
```
Test.java
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
/**
* 擴(kuò)展匿名內(nèi)部類
* 什么叫匿名內(nèi)部類:
* 沒有名字的內(nèi)部類,用法類似接口實現(xiàn)多態(tài)
*
* 案例:手機(jī)功偿、電腦類實現(xiàn)充電的功能
*
* 應(yīng)用場景:
* 當(dāng)需要實例化多次僧凤,調(diào)多次重寫方法時顿肺,選擇接口實現(xiàn)多態(tài)
* 當(dāng)只實例化一次去調(diào)重寫方法時牧愁,選擇匿名內(nèi)部類
*
*
*
*/
public class Test {
public static void main(String[] args) {
//比較器:接口實現(xiàn)多態(tài)方式
//Map<Student, Integer> map = new TreeMap<>(new MyComparator());
//匿名內(nèi)部類
Map<Student, Integer> map = new TreeMap<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
//按自己的規(guī)則進(jìn)行排序:先按年齡升序排序;年齡相等刑桑,則按姓名降序
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
}
}
```