Set集合中:重写:hashCode和equals方法是为了保证存入的对象不一样,
然后实现接口Comparable,是为了是对象具有可比性,可以在TreeSet集合中可以对存入的集合进行比较
当你没有实现hashCode和equals方法,那么不能保证集合对象的唯一性,但是如果你自定义了比较器(Comparator接口),
那么集合会根据你的比较器对存入的集合进行排序,如果相等那么则会排序存入一个。- public class StuNameComparator implements Comparator<Student> {
- /*按照姓名排序,如果姓名相同,那么按照年龄排序*/
- public int compare(Student o1, Student o2) {
- int num = o1.getName().compareTo(o2.getName());
- if (num == 0) {
- return o1.getAge() - o2.getAge();
- }
- return num;
- }
- }
- public class Student /*implements Comparable<Student> */{// 十七具有比较性,防止排序的出现异常
- private String name;// 姓名
- private int age;// 年龄
- public Student(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public int getAge() {
- return age;
- }
- // /* 重写hashCode()方法 */
- // public int hashCode() {
- // return this.name.hashCode() + this.age * 12;
- // }
- //
- // /* 重写equals方法 */
- // public boolean equals(Object ob) {
- // if (!(ob instanceof Student))
- // throw new ClassCastException("不是Student对象");
- // Student stu = (Student) ob;
- // return this.name.equals(stu.getName()) && this.age == stu.getAge();
- //
- // }
- //
- // /*
- // * 覆写CompareTo方法 先比较年龄,然后比较姓名
- // */
- // public int compareTo(Student stu) {
- // int num = this.age - stu.age;
- // if (num == 0) {
- // return this.name.compareTo(stu.name);
- // }
- // return num;
- //
- // }
- }
- public class TreeMapDemo {
- public static void main(String[] args) {
- /* 定义HashMap,里面存储的是Student和地址 */
- TreeMap<Student, String> map = new TreeMap<Student, String>(new StuNameComparator());
- map.put(new Student("java03", 23), "北京");
- map.put(new Student("net02", 21), "上海");
- map.put(new Student("net03", 26), "广州");
- map.put(new Student("java01", 24), "南京");
- map.put(new Student("net03", 26), "广州");
-
- Set<Student> set = map.keySet();
- Iterator<Student> it = set.iterator();
- while (it.hasNext()) {
- Student stu = it.next();
- String name = stu.getName();
- int age = stu.getAge();
- String address = map.get(stu);
- System.out.println(name + ":" + age + ":" + address);
- }
- }
- }
- public class TreeMapDemo {
- public static void main(String[] args) {
- /* 定义HashMap,里面存储的是Student和地址 */
- TreeMap<Student, String> map = new TreeMap<Student, String>(new StuNameComparator());
- map.put(new Student("java03", 23), "北京");
- map.put(new Student("net02", 21), "上海");
- map.put(new Student("net03", 26), "广州");
- map.put(new Student("java01", 24), "南京");
- map.put(new Student("net03", 26), "广州");
-
- Set<Student> set = map.keySet();
- Iterator<Student> it = set.iterator();
- while (it.hasNext()) {
- Student stu = it.next();
- String name = stu.getName();
- int age = stu.getAge();
- String address = map.get(stu);
- System.out.println(name + ":" + age + ":" + address);
- }
- }
- }
复制代码 结果:
java01:24:南京
java03:23:北京
net02:21:上海
net03:26:广州
希望对你有帮助!
|