标签:compare
不同数据结构判断元素是否相同的比较原理 arraylist equals hashset hashCode equals treeset 自定义比较器的compare的return 0 或是元素自身的compareTo的rutren 0 treeset的看下面的例子 class TreeSetDemo3 { public static void main(String[] args) { TreeSet ts = new TreeSet(new StudentComparatorByName());//比较器 //TreeSet ts = new TreeSet();//元素自身 ts.add(new Student("lisi0",30)); ts.add(new Student("lisixx",29)); ts.add(new Student("lisi9",29)); ts.add(new Student("lisi8",38)); ts.add(new Student("lisixx",29)); ts.add(new Student("lisi4",14)); //ts.add(new Student(39)); ts.add(new Student("lisi7",27)); System.out.println(ts); } } class StudentComparatorByName implements Comparator { public int compare(Object o1,Object o2) { Student s1 = (Student)o1; Student s2 = (Student)o2; int num = s1.getName().compareTo(s2.getName()); return num==0?new Integer(s1.getAge()).compareTo(new Integer(s2.getAge())):num; } } //同姓名同年龄的学生视为同一个学生。按照学生的年龄排序。 class Student implements Comparable { private int age; private String name; Student(String name,int age) { this.age = age; this.name = name; } public int compareTo(Object obj) { Student stu = (Student)obj; int num = new Integer(this.age).compareTo(new Integer(stu.age)); return num==0?this.name.compareTo(stu.name):num; /* if(this.age>stu.age) return 1; if(this.age==stu.age) return this.name.compareTo(stu.name); return -1; */ /**/ } public int getAge() { return age; } public String getName() { return name; } public String toString() { return name+"::"+age; } }
标签:compare
原文地址:http://11760512.blog.51cto.com/11750512/1853294