程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> collection-大神請進,幫忙看下這個Collection的排序。

collection-大神請進,幫忙看下這個Collection的排序。

編輯:編程綜合問答
大神請進,幫忙看下這個Collection的排序。

package com.jeffge;

import java.util.*;

public class StringSorting {
public static void main(String[] args) {
ArrayList persons = new ArrayList();
persons.add(new Person("Sam", 25));
persons.add(new Person("Sam", 35));
persons.add(new Person("Tom", 25));
persons.add(new Person("Tom", 35));
persons.add(new Person("Jeff", 25));
persons.add(new Person("Jeff", 35));
persons.add(new Person("Herry", 25));
persons.add(new Person("Herry", 35));
persons.add(new Person("Kim", 25));
persons.add(new Person("Kim", 35));
persons.add(new Person("Matthew", 25));
persons.add(new Person("Matthew", 35));
persons.add(new Person("Chris", 25));
persons.add(new Person("Chris", 35));
persons.add(new Person("Jakes", 25));
persons.add(new Person("Jakes", 35));
persons.add(new Person("Josh", 25));
persons.add(new Person("Josh", 35));
String expected = persons.toString();
println(persons);
Collections.shuffle(persons);

    Collections.sort(persons, new PersonComparator());

    String result = persons.toString();

    println("It is now   : "+result);
    println("It should be: " + expected);

    if(result.equals(expected)){
        println("It works!");
    } else {
        println("Keep trying!");
    }

}

private static void println(Object s) {
    System.out.println(s);
}


private static class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return name + "-" + age ;
    }


}


private static class PersonComparator implements Comparator<Person> {
    @Override
    public int compare(Person a, Person b) {
        return 0;
    }
}

}
請問 最下面實現的那個Compare 接口 怎麼寫 才能執行呀。 先按照名字排序,如果名字一樣,然後按照年齡排序

最佳回答:


private static class PersonComparator implements Comparator {
@Override
public int compare(Person a, Person b) {
if(a.name.equalsIgnoreCase(b.name)){
//年齡是按照從小到大的排列
if(a.age < b.age){
return -1;
}else if(a.age > b.age){
return 1;
}else{
return 0;
}
}else{
return a.name.compareTo(b.name);
}

}
kaseyhebe
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved