比较器。如何按年龄排序,但如果名称是“A”,则将其移至列表末尾?

huangapple go评论79阅读模式
英文:

Comparator. How to sort by age, but if name is "A", move it to the end of list?

问题

我有下一个任务:

我有一个对象MyObject:

MyObject {
  private String name;
  private int age;
}

使用Comparator的compare()方法实现,我必须按照age对MyObject的列表进行排序,但如果MyObject的name是"A",这个元素应该被移到列表的末尾。列表中不应该包含两个name为"A"的元素,所以我们会忽略这种情况。

我写了下面的代码,但它不起作用:

@Override
public int compare(MyObject myObject, MyObject t1) {
  if (myObject.getName().equals("A")) {
    return 1;
  } else if (myObject.getAge() == t1.getAge()) {
    return 0;
  } else if (myObject.getAge() > t1.getAge()) {
    return 1;
  } else {
    return -1;
  }
}
实际上我并不觉得它不起作用因为我不理解在这种情况下使用了哪种排序算法
英文:

I have the next task:

I have object MyObject:

MyObject {
  private String name;
  private int age;
}

Using the Comparator compare() method implementation, I have to sort the list of MyObject by age, but if the name of MyObject is "A", this element should be moved to the end of the list. The list shouldn't contain 2 elements with "A" name, so we ignore this case.

I've written the next code, but it doesn't work

@Override
public int compare(MyObject myObject, MyObject t1) {
if (myObject.getName().equals("A")) {
  return 1;
}else if (myObject.getAge() == t1.getAge()) {
  return 0;
} else if (myObject.getAge() > t1.getAge()) {
  return 1;
} else {
  return -1;
}
}

Actually I don't surprised that it doesn't work, as I don't understand which sorting algorithm is used in this case.

答案1

得分: 3

    @Override
    public int compare(MyObject m1, MyObject m2) {
       if (m1.getName().equals("A") && !m2.getName().equals("A")) {
          return 1;
       }else if (!m1.getName().equals("A") && m2.getName().equals("A")) {
          return -1;
       } else {
          return Integer.compare(m1.getAge(), m2.getAge());
       }
    }
英文:

Try something like:

@Override
public int compare(MyObject m1, MyObject m2) {
   if (m1.getName().equals("A") && !m2.getName().equals("A")) {
      return 1;
   }else if (!m1.getName().equals("A") && m2.getName().equals("A")) {
      return -1;
   } else {
      return Integer.compare(m1.getAge(), m2.getAge());
   }
}

huangapple
  • 本文由 发表于 2020年8月31日 23:57:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63674165.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定