列表中有两个不同的对象需要排序

时间:2016-02-11 09:51:02

标签: java arraylist collections

ArrayList有两个不同的类/对象

   - Student class has 2 fields --> NAME and ID

   - Employee class has 2 fields --> NAME and ID  

需要根据 ID字段进行排序。能不能请你帮我谢谢。

我的建议是使用比较器可以帮我解决java代码。

class Emp {
  String name;
  int number;
  public String getName() { return name; }
  public void setName(String name) { this.name = name; }
  public int getNumber() { return number; }
  public void setNumber(int number) { this.number = number; }
}

class Student {
  String name;
  int number;
  public String getName() { return name; }
  public void setName(String name) { this.name = name; }
  public int getNumber() { return number; }
  public void setNumber(int number) { this.number = number; }
}

class empcomparator implements Comparator {
  @Override
  public int compare(Object o1, Object o2) {
   String a = ((emp) o1).getName();
   String b = ((student) o2).getName();
   return a.compareTo(b); return 1;
  }
}

主要类我的代码:

Emp emp = new Emp();
emp.setName("test1");
emp.setNumber(11);
Student stud= new Student ();
stud.setName("test2");
stud.setNumber(22);
List<Object> studentlist = new ArrayList<Object>();
studentlist.add(emp);
studentlist.add(stud);
Collections.sort(studentlist, new empcomparator());

列表包含100个这样的对象需要根据id进行排序。请建议我好主意。

1 个答案:

答案 0 :(得分:3)

创建一个包含姓名和ID字段的Person课程。

创建StudentEmployee类,以便它们从Person类继承。

然后,您可以制作一个ArrayList<Person>,其中包含两个元素,您可以使用Comparator<Person>对其进行排序。

修改您的代码:

abstract class Person implements Comparable<Person> {
    String name;
    int number;
    public Person( final int id, final String name ){
        setNumber( id );
        setName( name );
    }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getNumber() { return number; }
    public void setNumber(int number) { this.number = number; }
    public int compareTo( final Person otherPerson ){
      return Integer.compare( this.getNumber(), otherPerson.getNumber() );
    }
    public abstract String toString();
}

class Emp extends Person {
    public Emp( final int id, final String name ){
        super( id, name );
    }
    public String toString(){ return String.format( "Employee: %d, %s", getNumber(), getName() ); }
}

class Student extends Person {
    public Student( final int id, final String name ){
        super( id, name );
    }
    public String toString(){ return String.format( "Student: %d, %s", getNumber(), getName() ); }
}

public static void main( final String[] args ){
    ArrayList<Person> people = new ArrayList<Person>();
    people.add( new Student( 23, "Bob" ) );
    people.add( new Emp( 12, "Alice" ) );
    people.add( new Student( 3, "Carol" ) );
    people.add( new Emp( 5, "Denise" ) );
    System.out.println( people.toString() );
    Collections.sort( people );
    System.out.println( people.toString() );
}