我正在编写一段编译好的代码,但有点粗糙,可以进行优化。是否有更好或更简单的方法来做到这一点。我也是以正确的方式使用compareTo()方法吗?我试图使用不同的方法使代码比下面的示例更清晰,更快。
import java.util.ArrayList;
public class Sort {
public ArrayList<Name> sort(ArrayList<Name> names) {
ArrayList<Name> results;
results = new ArrayList<Name>();
do {
Name firstName = new Name("zzz", "zzz");
for (int i = 0; i < names.size(); i++)
if (names.get(i).getFirstName()
.compareTo(firstName.getFirstName()) < 0
|| names.get(i).getFirstName() == firstName
.getFirstName() && names.get(i).getSurName()
.compareTo(firstName.getSurName()) < 0)
firstName = new Name(names.get(i).getFirstName(),
names.get(i).getSurName());
results.add(firstName);
names.remove(firstName);
} while (names.size() > 0);
return results;
}
}
class Name {
private String firstName;
private String surName;
public Name() {
}
public Name(String firstName, String surName) {
this.firstName = firstName;
this.surName = surName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSurName() {
return surName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public String toString() {
return firstName + " " + surName;
}
public boolean equals(Object other) {
return firstName == ((Name) other).firstName
&& surName == ((Name) other).surName;
}
}
答案 0 :(得分:2)
有没有更好或更简单的方法来做到这一点。我也是以正确的方式使用compareTo()方法吗?
是几个问题:
==
firstName == ((Name) other).firstName
因此,请定义您自己的比较器并使用它:
Collections.sort(names, new MyNamesComparator());
答案 1 :(得分:1)
如果您想要效率,我建议您使用内置排序O(N * log N)
// in Java 7
Arrays.sort(names, new Comparator<Name, Name>()) {
public int compare(Name n1, Name n2) {
int cmp = n1.firstName.compareTo(n2.firstName);
if (cmp == 0)
cmp = n1.lastName.compareTo(n2.lastName);
}
});
// in Java 8
names = names.stream()
.sorted(Comparator.comparing(Name::getFirstName)
.andThen(Name::getLastName))
.collect(Collectors.toList());