0

私は従業員のコレクションを持っています。各従業員は 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
                }
            });
4

4 に答える 4

2

夕食を食べながらちょっと考えてみたら、こっちの方が好き。

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-15T18:41:55.537 に答える
1

3つのテストを実行できませんでしたか?

非負は負の前に来ます。 returnちょうど 1 つが負の場合。

両方が負の場合、大きい方の値が小さい方の値より前になります。

両方とも負でない場合、小さい方の値が大きい方の値より前になります。

于 2013-01-15T17:44:53.950 に答える
0

Compare は、最初の引数が 2 番目の引数より小さい、等しい、または大きい場合に、負の整数、ゼロ、または正の整数を返します。

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]

于 2013-01-15T17:57:29.603 に答える
0

それはあいまいですが、あなたはすることができます

Integer.compare(x >= 0 ? x + Integer.MIN_VALUE : ~x, y >= 0 ? y + Integer.MIN_VALUE);

またはさらにあいまいな

Integer.compare(x ^ (-1 << ~(x >> -1)), y ^ (-1 << ~(y >> -1)))

注: longs についても同じ式が機能します ;)

これは [0, Integer.MAX_VALUE] を [Integer.MIN_VALUE, -1] にマップし、[Integer.MIN_VALUE, -1] を [0, Integer.MAX_VALUE] に反転します。

于 2013-01-15T21:49:08.223 に答える