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