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);
}
}