kaseyhebe 2015-01-21 03:06 采纳率: 21.1%
浏览 2159
已采纳

大神请进,帮忙看下这个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 接口 怎么写 才能执行呀。 先按照名字排序,如果名字一样,然后按照年龄排序

  • 写回答

7条回答 默认 最新

  • GalinaY 2015-01-21 05:51
    关注

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

    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置