1. TreeMap
- TreeMap存储Key-Value对时,需要根据Key对key-value对进行排序。TreeMap可以保证所有的Key-Value对处于有序状态。
- TreeMap的Key的排序:
- 自然排序:TreeMap的所有的Key必须实现Comparable接口,而且所有的Key应该是同一个类的对象,否则将会抛出ClassCastException
- 定制排序:创建TreeMap时,传入一个Comparator对象,该对象负责对TreeMap中的所有key进行排序。此时不需要Map的key实现Comparable接口
2. Person
package com.atguigu.javase.lesson7;
public class Person implements Comparable{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
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 "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age;
}
@Override
public int hashCode() {
return age;
}
@Override
public int compareTo(Object o) {
if(o instanceof Person){
Person person = (Person)o;
return this.name.compareTo(person.name);
}else{
throw new ClassCastException("不能转为Person类型");
}
}
}
3. MapTest-Comparator
package test.com.atguigu.javase.lesson7;
import com.atguigu.javase.lesson7.Person;
import com.atguigu.javase.lesson7.Person1;
import org.junit.Test;
import java.util.*;
/**
* MapTest Tester.
*/
public class MapTestTest {
@Test
public void testTreeMapWithComparator(){
Map map = new TreeMap();
map.put(new Person("CC",12), "CC");
map.put(new Person("BB",12), "BB");
map.put(new Person("AA",12), "AA");
map.put(new Person("DD",12), "DD");
map.put(new Person("EE",12), "EE");
Set keySet = map.keySet();
Iterator iterator = keySet.iterator();
while(iterator.hasNext()){
Object key = iterator.next();
Object val = map.get(key);
System.out.println(key + " : " + val);
}
}
}
4. MapTest-Comparable
package test.com.atguigu.javase.lesson7;
import com.atguigu.javase.lesson7.Person;
import com.atguigu.javase.lesson7.Person1;
import org.junit.Test;
import java.util.*;
/**
* MapTest Tester.
*/
public class MapTestTest {
@Test
public void testTreeMapWithComparable(){
Comparator comparator = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof Person1 && o2 instanceof Person1){
Person1 p1 = (Person1)o1;
Person1 p2 = (Person1)o2;
return p1.getName().compareTo(p2.getName());
}else{
throw new ClassCastException("不能转换为Person1类型");
}
}
};
Map map = new TreeMap(comparator);
map.put(new Person1("CC",12), "CC");
map.put(new Person1("BB",12), "BB");
map.put(new Person1("AA",12), "AA");
map.put(new Person1("DD",12), "DD");
map.put(new Person1("EE",12), "EE");
Set keySet = map.keySet();
Iterator iterator = keySet.iterator();
while (iterator.hasNext()){
Object key = iterator.next();
Object val = map.get(key);
System.out.println(key + " : " + val);
}
}