如何按ID排序此对象 [英] How do I sort this object by id
问题描述
我有这段代码。我的比较器是否正确?
公共抽象类人员实现可比较< person> {
private int _id;
private int _phoneNumber;
private String _name;
private List< notification> _listNotifications;
@Override
public int compareTo(Person p){
return this.getId() .compareTo(p.getId());
}
我的尝试:
我试图编译并检查它是否有效但是它不起作用
I have this piece of code. Is my comparator correct?
public abstract class Person implements Comparable<person> {
private int _id;
private int _phoneNumber;
private String _name;
private List<notification> _listNotifications;
@Override
public int compareTo(Person p){
return this.getId().compareTo(p.getId());
}
What I have tried:
I was trying to compile and checks if it works but it is not working
推荐答案
试试
Try
class Person implements Comparable<Person>
{
private int _id;
private String _name;
public int getId(){ return _id;}
public String getName(){ return _name; }
Person( int id, String name){ _id = id; _name = name; }
@Override
public int compareTo(Person p)
{
return Integer.compare(this.getId(), p.getId());
}
public static void main( String arg[])
{
Person p1 = new Person( 12, "Boo");
Person p2 = new Person( 10, "Foo");
String is = p1.compareTo(p2) > 0 ? "is" : "is not ";
System.out.printf("%s %s bigger than %s", p1.getName(), is, p2.getName());
}
}
[update]
遵循请求...
[update]
Following the kind request...
import java.util.*;
class Person implements Comparable<Person>
{
private int _id;
private String _name;
public int getId(){ return _id;}
public String getName(){ return _name; }
Person( int id, String name){ _id = id; _name = name; }
@Override
public int compareTo(Person p)
{
return Integer.compare(this.getId(), p.getId());
}
public static void main( String arg[])
{
Person p1 = new Person( 12, "Boo");
Person p2 = new Person( 10, "Foo");
ArrayList <Person> alp=new ArrayList<Person>();
alp.add(p1);
alp.add(p2);
Collections.sort(alp);
for ( Person p : alp)
System.out.printf("%s\n", p.getName());
Collections.sort( alp, new NameComparator() );
for ( Person p : alp)
System.out.printf("%s\n", p.getName());
}
}
class NameComparator implements Comparator<Person>
{
@Override
public int compare(Person p1, Person p2) {
return p1.getName().compareTo(p2.getName());
}
}
[/ update]
这篇关于如何按ID排序此对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!