java Comparator 實現不一樣的排序
阿新 • • 發佈:2019-02-13
程式設計師面試寶典中,大家應該都看過各種排序方法:
冒泡
選擇
插入
快速
堆排序
等等..
這些針對的都是簡單的資料型別,比如數值型int型別,當遇到實際情況中的複雜排序,比如對一個公司的員工,依據姓名,年齡,性別等不同的因素綜合排序的情形,用上面的排序方法,將無法實現。但是不要害怕~java中有大神器:Comparator介面
我們來看下原始碼,簡單的讓你不知道該怎麼做..
就2個方法,那麼實現複雜的排序,我們只要實現該介面中的compare介面就OK了。public interface Comparator<T> { /** * Compares its two arguments for order. Returns a negative integer, * zero, or a positive integer as the first argument is less than, equal * to, or greater than the second.<p> * * In the foregoing description, the notation * <tt>sgn(</tt><i>expression</i><tt>)</tt> designates the mathematical * <i>signum</i> function, which is defined to return one of <tt>-1</tt>, * <tt>0</tt>, or <tt>1</tt> according to whether the value of * <i>expression</i> is negative, zero or positive.<p> * * The implementor must ensure that <tt>sgn(compare(x, y)) == * -sgn(compare(y, x))</tt> for all <tt>x</tt> and <tt>y</tt>. (This * implies that <tt>compare(x, y)</tt> must throw an exception if and only * if <tt>compare(y, x)</tt> throws an exception.)<p> * * The implementor must also ensure that the relation is transitive: * <tt>((compare(x, y)>0) && (compare(y, z)>0))</tt> implies * <tt>compare(x, z)>0</tt>.<p> * * Finally, the implementor must ensure that <tt>compare(x, y)==0</tt> * implies that <tt>sgn(compare(x, z))==sgn(compare(y, z))</tt> for all * <tt>z</tt>.<p> * * It is generally the case, but <i>not</i> strictly required that * <tt>(compare(x, y)==0) == (x.equals(y))</tt>. Generally speaking, * any comparator that violates this condition should clearly indicate * this fact. The recommended language is "Note: this comparator * imposes orderings that are inconsistent with equals." * * @param o1 the first object to be compared. * @param o2 the second object to be compared. * @return a negative integer, zero, or a positive integer as the * first argument is less than, equal to, or greater than the * second. * @throws NullPointerException if an argument is null and this * comparator does not permit null arguments * @throws ClassCastException if the arguments' types prevent them from * being compared by this comparator. */ <span style="font-size:18px;"> int compare(T o1, T o2);</span> /** * Indicates whether some other object is "equal to" this * comparator. This method must obey the general contract of * {@link Object#equals(Object)}. Additionally, this method can return * <tt>true</tt> <i>only</i> if the specified object is also a comparator * and it imposes the same ordering as this comparator. Thus, * <code>comp1.equals(comp2)</code> implies that <tt>sgn(comp1.compare(o1, * o2))==sgn(comp2.compare(o1, o2))</tt> for every object reference * <tt>o1</tt> and <tt>o2</tt>.<p> * * Note that it is <i>always</i> safe <i>not</i> to override * <tt>Object.equals(Object)</tt>. However, overriding this method may, * in some cases, improve performance by allowing programs to determine * that two distinct comparators impose the same order. * * @param obj the reference object with which to compare. * @return <code>true</code> only if the specified object is also * a comparator and it imposes the same ordering as this * comparator. * @see Object#equals(Object) * @see Object#hashCode() */ <span style="font-size:18px;"> boolean equals(Object obj);</span> }
具體程式碼如下:
執行結果:package someTest; import java.util.Comparator; class Person { String firstname,lastname; Boolean sex; Integer age; public Person(String firstname,String lastname,Boolean sex,Integer age) { this.firstname = firstname; this.lastname = lastname; this.sex = sex; this.age = age; } public String getFirstName() { return firstname; } public String getLastName() { return lastname; } public Boolean getSex() { return sex; } public Integer getAge() { return age; } //為了輸入方便,重寫了toString() public String toString() { return firstname +" "+lastname+" "+(sex.booleanValue()?"男":"女")+" "+age; } } //end person public class CompareObject implements Comparator<Object> { @Override public int compare(Object o1, Object o2){ if (o1 instanceof String) { return compareImp( (String) o1, (String) o2); }else if (o1 instanceof Integer) { return compareImp( (Integer) o1, (Integer) o2); }else if (o1 instanceof Boolean) { return compareImp( (Boolean) o1, (Boolean) o2); } else if (o1 instanceof Person) { return compareImp( (Person) o1, (Person) o2); }else { //根據需要擴充套件compare函式 System.err.println("未找到合適的比較器"); return 1; } } //過載 public int compareImp(String o1, String o2) { String s1 = (String) o1; String s2 = (String) o2; int len1 = s1.length(); int len2 = s2.length(); int n = Math.min(len1, len2); char v1[] = s1.toCharArray(); char v2[] = s2.toCharArray(); int pos = 0; while (n-- != 0) { char c1 = v1[pos]; char c2 = v2[pos]; if (c1 != c2) { return c1 - c2; } pos++; } return len1 - len2; } //過載 public int compareImp(Integer o1, Integer o2) { int val1 = o1.intValue(); int val2 = o2.intValue(); return (val1 < val2 ? -1 : (val1 == val2 ? 0 : 1)); } //過載 public int compareImp(Boolean o1, Boolean o2) { return (o1.equals(o2)? 0 : (o1.booleanValue()==true?1:-1)); } /*實體類的排序 * 進行姓排序,誰的姓拼音靠前,誰就排前面。 * 然後對名字進行排序。如果同名,女性排前頭。 * 如果名字和性別都相同,年齡小的排前頭。 * */ //過載 public int compareImp(Person o1, Person o2) { String firstname1 = o1.getFirstName(); String firstname2 = o2.getFirstName(); String lastname1 = o1.getLastName(); String lastname2 = o2.getLastName(); Boolean sex1 = o1.getSex(); Boolean sex2 = o2.getSex(); Integer age1 = o1.getAge(); Integer age2 = o2.getAge(); int compareFirstName = compare(firstname1, firstname2); int compareLastName = compare(lastname1, lastname2); int compareSex = compare(sex1, sex2); if (compareFirstName != 0) { return compareFirstName; } if (compareLastName != 0) { return compareLastName; } if (compareSex != 0) { return compareSex; } return compare(age1, age2); } /*public boolean equals(Object obj){ return true; }*/ public static void main(String[] args) { Person[] person = new Person[] { new Person("zhangsan", "gg", Boolean.TRUE, new Integer(27)), new Person("lisi", "mm", Boolean.TRUE, new Integer(27)), new Person("wangwu", "mm", Boolean.FALSE, new Integer(27)), new Person("wangwu", "mm", Boolean.FALSE, new Integer(10)) }; for (int i = 0; i < person.length; i++) { if(i==0) System.out.println("排序前:"); System.out.println("before sort=" + person[i]); } java.util.Arrays.sort(person, new CompareObject()); for (int i = 0; i < person.length; i++) { if(i==0) System.out.println("排序後:"); System.out.println("after sort=" + person[i]); } } }
排序前:
before sort=zhangsan gg 男 27
before sort=lisi mm 男 27
before sort=wangwu mm 女 27
before sort=wangwu mm 女 10
排序後:
after sort=lisi mm 男 27
after sort=wangwu mm 女 10
after sort=wangwu mm 女 27
after sort=zhangsan gg 男 27
注:在實現Comparator介面時,並沒有實現equals方法,可程式並沒有報錯,原因是實現該介面的類也是Object類的子類,而Object類已經實現了equals方法