问题描述
- 大神请进,帮忙看下这个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);
}
}
解决方案二:
public int compare(Person a, Person b) {
if (a.name.equals(b.name))
return a.age.compareTo(b.age);
else
return a.name.compareTob.name;
}
解决方案三:
public int compare(Person a, Person b) {
if (a.name.equals(b.name)) //名字相同按age排
return a.age.compareTo(b.age);
else
return a.name.compareTo(b.name); //按名字排
}
解决方案四:
private static class PersonComparator implements Comparator<Person> {
@Override
public int compare(Person a, Person b) {
return a.age.compareTo(b.age);
}
}
解决方案五:
http://www.tutorialspoint.com/java/java_using_comparator.htm
解决方案六:
@兔子党-督察 麻烦大伙帮帮忙呀
解决方案七:
return a.age > b.age;