1.存储结构:红黑树
2.实现了SortedMap接口(是Map的子接口),可以对key自动排序。
3.实例代码:Student类和Demo03
如果出现类转换异常 参考【TreeSet(红黑树)】
package com.map;
import java.util.Objects;
public class Student implements Comparable<Student>{
private String name;
private int stuNo;
public Student(String name, int stuNo) {
this.name = name;
this.stuNo = stuNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStuNo() {
return stuNo;
}
public void setStuNo(int stuNo) {
this.stuNo = stuNo;
}
@Override
public String toString() {
return "Student [name=" + name + ", stuNo=" + stuNo + "]";
}
@Override
public int compareTo(Student o) {
int n1 = this.getStuNo()-o.getStuNo();
int n2 = this.name.compareTo(o.getName());
return n1==0?n1:n2;
}
}
package com.map;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* TreeMap集合的使用
* 存储结构:红黑树
*/
public class Demo03 {
public static void main(String[] args) {
//创建集合
TreeMap<Student, String> treeMap = new TreeMap<>();
//创建学生对象
Student s1 = new Student("小王", 100);
Student s2 = new Student("小刘", 101);
Student s3 = new Student("小方", 102);
Student s4 = new Student("小舟", 103);
//1添加数据
treeMap.put(s1,"北京");
treeMap.put(s2,"上海");
treeMap.put(s3,"福建");
treeMap.put(s4,"重庆");
System.out.println("学生个数:"+treeMap.size());
System.out.println(treeMap);
//2删除数据
treeMap.remove(s1);
System.out.println(treeMap);
//3遍历数据
System.out.println("--------keySet()-----------");
Set<Student> set = treeMap.keySet();
for(Student s : set){
System.out.println(s);
}
System.out.println("--------entrySet()-----------");
Set<Map.Entry<Student, String>> entries = treeMap.entrySet();
for(Map.Entry<Student, String> entry : entries){
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}
结果: