package edu.wtbu;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class Demo01 {
public static void main(String[] args) {
//新建集合
TreeMap<Student, String> treeMap = new TreeMap<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int n1=o1.getStuNo()-o2.getStuNo();
return n1;
}
});
//1.添加元素
Student s1 = new Student("张三", 16);
Student s2 = new Student("李四", 17);
Student s3 = new Student("王五", 18);
treeMap.put(s1,"湖北");
treeMap.put(s2,"湖南");
treeMap.put(s3,"北京");
System.out.println("元素个数:"+treeMap.size());//元素个数:3
System.out.println(treeMap);//{Student{name='张三', stuNo=16}=湖北, Student{name='李四', stuNo=17}=湖南, Student{name='王五', stuNo=18}=北京}
//2.删除元素
//treeMap.remove(s1);
treeMap.remove(new Student("张三", 16));
System.out.println("元素个数:"+treeMap.size());//元素个数:2
System.out.println(treeMap);//{Student{name='李四', stuNo=17}=湖南, Student{name='王五', stuNo=18}=北京}
//3.遍历
//1.使用KeySet
Set<Student> keySet = treeMap.keySet();
for (Student key:
keySet) {
System.out.println(key+"--------"+treeMap.get(key));
}
//2.使用EntrySet
Set<Map.Entry<Student, String>> entrySet = treeMap.entrySet();
for (Map.Entry<Student, String> key:
entrySet) {
System.out.println(key);
}
//4.判断
System.out.println(treeMap.containsKey(s2));//true
System.out.println(treeMap.isEmpty());//false
}
}
package edu.wtbu;标签:stuNo,name,treeMap,TreeMap,Student,使用,public,out From: https://www.cnblogs.com/123456dh/p/17140276.html
import java.util.Objects;
public class 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 == null || getClass() != o.getClass()) return false;
// Student student = (Student) o;
// return stuNo == student.stuNo && Objects.equals(name, student.name);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name, stuNo);
// }
}