比较器的 java,如何在Java中实现比较器

This program is to implement comparator

everything is fine

import java.util.*;

public class Solocomparator implements Comparator {

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 a1=new ArrayList();

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

}

}

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

解决方案

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 {

@Override

public int compare(Solomon o1, Solomon o2) {

return o1.getAge() - o2.getAge();

}

}

and/or

public class SolomanNameComparator implements Comparator {

@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 a1 = new ArrayList();

a1.add(new Solomon(21, "solomon"));

a1.add(new Solomon(26, "solomons"));

a1.add(new Solomon(20, "solomonjking"));

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值