treemap
treeMap
类需要实现comparable
需要重写compareTo
import java.util.TreeMap;
public class Demo01 {
public static void main(String[] args) {
//创建集合
TreeMap<Student, String> treeMap = new TreeMap<>();
//1添加元素
Student s1 = new Student("孙悟空", 01);
Student s2 = new Student("猪八戒", 02);
Student s3 = new Student("沙和尚", 03);
treeMap.put(s1, "北京");
treeMap.put(s2, "上海");
treeMap.put(s3, "北京");
System.out.println(treeMap);
}
}
package Collection.Map.Demo03;
import java.util.Objects;
public class Student implements Comparable <Student>{
private String name;
private int stuNo;
public Student() {
}
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 boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student student = (Student) o;
return getStuNo() == student.getStuNo() && Objects.equals(getName(), student.getName());
}
@Override
public int hashCode() {
return Objects.hash(getName(), getStuNo());
}
@Override
public int compareTo(Student o) {
//int n1 = this.name.compareTo(o.getName());
int n2 = this.stuNo-o.stuNo;
return n2;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现