英文:
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());
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论