标签:rgs 去除 rem cti eset public sys 结果 pre
**在使用TreeSet或者TreeMap来保存自定义对象时,必须让自定义对象的类实现Comparable接口,并重写其compareTo()方法,否则会报cannot be cast to java.lang.Comparable异常。*
package com.treemappractice;
/**
* 学生实体类
*/
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;
}
//去除重复 重写hashcode方法和equals方法
//重写hashcode方法进行内存地址的判断
@Override
public int hashCode() {
int n1 = this.name.hashCode();
int n2 = this.stuNo;
return n1 + n2;
}
//必须重写equals方法才能判断添加的对象是否重复
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (obj instanceof Student) {
Student person = (Student) obj;
if (this.name.equals(person.getName()) && this.stuNo == person.getStuNo()) {
return true;
}
}
return false;
}
@Override
public String toString() {
return "Student{" +
"name=‘" + name + ‘\‘‘ +
", stuNo=" + stuNo +
‘}‘;
}
public int compareTo(Student o) {
int n2=this.stuNo-o.getStuNo();
return n2;
}
}
package com.treemappractice;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
/**
* 联系TreeMap集合的使用
* 存储结构:红黑树
*/
public class TreeMapDemo01 {
public static void main(String[] args) {
//1.添加元素 定制比较器
// TreeMap<Student, String> treeMap = new TreeMap<Student, String>(new Comparator<Student>() {
// public int compare(Student o1, Student o2) {
// return 0;
// }
// });
TreeMap<Student, String> treeMap = new TreeMap<Student, String>();
Student stu1 = new Student("孙悟空", 100);
Student stu2 = new Student("猪八戒", 101);
Student stu3 = new Student("沙和尚", 102);
treeMap.put(stu1,"金箍棒");
treeMap.put(stu2,"菜耙子");
treeMap.put(stu3,"降魔杖");
System.out.println("元素的个数:"+treeMap.size());
System.out.println("集合内容:"+treeMap);
//2.删除
// treeMap.remove(stu1);
// System.out.println("删除之后元素的个数:"+treeMap.size());
// System.out.println("删除之后集合内容:"+treeMap);
//3.遍历
System.out.println("==========keySet==========");
for (Student key : treeMap.keySet()) {
System.out.println(key+"--"+treeMap.get(key));
}
System.out.println("==========entrySet==========");
for (Map.Entry<Student, String> stringEntry : treeMap.entrySet()) {
System.out.println(stringEntry.getKey()+"--"+stringEntry.getValue());
}
}
}
运行结果:
元素的个数:3
集合内容:{Student{name=‘孙悟空‘, stuNo=100}=金箍棒, Student{name=‘猪八戒‘, stuNo=101}=菜耙子, Student{name=‘沙和尚‘, stuNo=102}=降魔杖}
==========keySet==========
Student{name=‘孙悟空‘, stuNo=100}--金箍棒
Student{name=‘猪八戒‘, stuNo=101}--菜耙子
Student{name=‘沙和尚‘, stuNo=102}--降魔杖
==========entrySet==========
Student{name=‘孙悟空‘, stuNo=100}--金箍棒
Student{name=‘猪八戒‘, stuNo=101}--菜耙子
Student{name=‘沙和尚‘, stuNo=102}--降魔杖
标签:rgs 去除 rem cti eset public sys 结果 pre
原文地址:https://www.cnblogs.com/dongyaotou/p/14349870.html