如何在Java中实现比较器 [英] How to implement comparator in java

查看:165
本文介绍了如何在Java中实现比较器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该程序用于实现比较器

一切都很好

import java.util.*;
public class Solocomparator implements Comparator<Solocomparator> {

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

    public int compare(Solocomparator nam) {
        return (this.name).compareTo(nam.name);
    }

    public static void main(String[] args) {
        ArrayList<Solocomparator> a1=new ArrayList<Solocomparator>();
        a1.add(new Solocomparator(21,"solomon"));
        a1.add(new Solocomparator(26,"solomons"));
        a1.add(new Solocomparator(20,"solomonjking"));
        Collections.sort(a1,new Solocomparator());
        for(Solocomparator i:a1)
            System.out.println(i.age+":" + i.name);        
    }
}

在此程序中,我已经实现了比较器来对Arary进行排序按年龄列出,
问题似乎在此行中

in this program i have implemented comparator to sort the arary list by age , problem seems to be in this line of code

Collections.sort(a1,new Solocomparator());


推荐答案

可比 Comparator 是两个不同的接口,用于相似的目的。 Collections.sort 想要一个 Comparator ,这使您可以灵活地修改可以比较对象的默认方式(或不比较) ,取决于您要实现的目标)。

Comparable and Comparator are two different interfaces, used for similar purposes. Collections.sort wants a Comparator and this allows you the flexibility to modify the default way objects might be compared (or not, depends on what you want to achieve)

首先创建一个基础对象,其中包含您需要存储的值...

Start by creating a base object, which contains the values you need to store...

public class Solomon {
    private int age;
    private String name;

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

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

}

然后创建比较器可以比较所罗门实例的方式...

Then create a Comparator which can compare the instances of Solomon the way you need to...

public class SolomanAgeComparator implements Comparator<Solomon> {

    @Override
    public int compare(Solomon o1, Solomon o2) {
        return o1.getAge() - o2.getAge();
    }

}

和/或

public class SolomanNameComparator implements Comparator<Solomon> {

    @Override
    public int compare(Solomon o1, Solomon o2) {
        return o1.getName().compareTo(o2.getName());
    }

}

然后使用其中一个对列表值...

Then use either one to sort the List of values...

List<Solomon> a1 = new ArrayList<Solomon>();
a1.add(new Solomon(21, "solomon"));
a1.add(new Solomon(26, "solomons"));
a1.add(new Solomon(20, "solomonjking"));
Collections.sort(a1, new SolomanNameComparator());

这篇关于如何在Java中实现比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆