public class Students implements Comparable<Students>{
private String name;
private int stuNO;
public Students() {
}
public Students(String age, int stuNO) {
this.name = age;
this.stuNO = stuNO;
}
public String getName() {
return name;
}
public void setName(String age) {
this.name = age;
}
public int getStuNO() {
return stuNO;
}
public void setStuNO(int stuNO) {
this.stuNO = stuNO;
}
@Override
public String toString() {
return "Students{" +
"age='" + name + '\'' +
", stuNO=" + stuNO +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Students students = (Students) o;
return stuNO == students.stuNO && Objects.equals(name, students.name);
}
@Override
public int hashCode() {
return Objects.hash(name, stuNO);
}
@Override
public int compareTo(Students o) {
int n1=this.name.compareTo(o.getName());
int n2=this.stuNO-o.getStuNO();
return n2;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
package Map01;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Demo03_TreeMap {
public static void main(String[] args) {
TreeMap<Students,String> stu=new TreeMap<>();
Students p1=new Students("刘德华",20);
Students p2=new Students("李小龙",22);
Students p3=new Students("彭于晏",24);
System.out.println("数据的个数"+stu.size());
System.out.println(stu.toString());
stu.put(p1,"上海");
stu.put(p2,"北京");
stu.put(p3,"深圳");
stu.put(new Students("彭于晏",24),"深圳");
System.out.println("数据的个数"+stu.size());
System.out.println(stu.toString());
stu.remove(p1);
System.out.println("============使用keyset======================");
for (Students key : stu.keySet()) {
System.out.println(key+":"+stu.get(key));
}
System.out.println("============使用entryset遍历======================");
for (Map.Entry<Students, String> entry : stu.entrySet()) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51