我有一批员工。每个员工都有一个ID。此ID号的格式为-x >= 0 >= x。我必须将雇员排序为0...x -1...x。我该怎么做呢??
List<Employee> empSort = new ArrayList(em.getEmployees());
Collections.sort(empSort, new Comparator<Employee>() {
@Override
public int compare(Employee p1, Employee p2) {
// WHAT LOGIC SHOULD I DO THERE TO HAVE THEM
SORTED AS 0...x -1....-x
}
});发布于 2013-01-16 02:41:56
在晚餐的时候考虑了一下,我更喜欢这样。
int sign1 = (p1 >= 0) ? 1 : -1;
int sign2 = (p2 >= 0) ? 1 : -1;
int result = Integer.compare(sign2, sign1);
if( result == 0){
// same sign
result = sign1 * Integer.compare(p1, p2);
}
return result;输出仍然是:
[0, 0, 0, 1, 3, 5, -1, -2]发布于 2013-01-16 01:44:54
你能不能不做三个测试?
Non-negative先于negative。如果恰好有一个为负,则返回return。
如果两者都为负值,则较大的值出现在较小的值之前。
如果两者都为非负值,则较小的值位于较大的值之前。
发布于 2013-01-16 01:57:30
当第一个参数小于、等于或大于第二个参数时,Compare返回负整数、零或正整数。
if( p1.id * p2.id < 0 ) {
// opposite sign
// if p1 is negative, p2 is positive, p1 is greater than p2
// otherwise p1 is positive, p2 is negative, p1 is less than p2
return -p1.id;
}
if( p1.id > 0 && p2.id > 0 || p1.id + p2.id >= 0) {
// both positive, normal ordering or a zero and a positive number, also normal ordering
return p1.id - p2.id;
}
if( p1.id <0 && p2.id < 0 ){
// both negative, inverse ordering
return p2.id - p1.id;
}
// zero and a negative number, zero comes first
if( p1.id == 0 ) {
return -1;
}
return 1;0,0,0,1,3,5,-1,-2
https://stackoverflow.com/questions/14343513
复制相似问题