我需要编写比较器的帮助:-

我想要这个输出:-

Martin Joseph Male 4/2/1979 Green
Ramya  Patil  Female 5/4/2009 Red
Don    kelly  Male   5/6/1986 Yellow
Van    Shinde female 3/4/1984 Green


但是我得到以下输出:-

Output 1:
 Van    Shinde female 3/4/1984 Green
 Don    kelly  Male   5/6/1986 Yellow
 Ramya  Patil  Female 5/4/2009 Red
 Martin Joseph Male 4/2/1979 Green


我该如何按姓氏排序,以保持列表顺序完整..我的意思是我要输出按姓氏先排列的女性,然后按姓氏排列的男性...请帮助我。

这是我使用性别比较器后使用的比较器:-

public class LastNameComparator implements Comparator<Person> {


public int compare(Person name_one, Person name_two) {
        // TODO Auto-generated method stub
        if(name_one.getGender().equals(name_two.getGender())){
            return name_one.getLast_name().compareTo(name_two.getLast_name());

        }else{
        return name_one.getLast_name().compareTo(name_two.getLast_name());
        }
    }

}

最佳答案

public int compare(Person a, Person b) {
  int ret = a.getGender().compareTo(b.getGender());
  if (ret == 0) {
    ret = a.getLastName().compareTo(b.getLastName());
  }
  return ret;
}

关于java - 为我的工作面试代码示例编写比较器所需的帮助,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1557791/

10-16 01:40