0

您好,我正在尝试先从 ArrayList 中的最高值排序浮点数列表,然后再到最低值。

CustomObject 持有一个对象,该对象的值为 float。

到目前为止,我正在这样做(失败,没有做任何事情)。

Collections.sort(mNaturalResistanceBoxes, new Comparator < PercentageBox > () {
    public int compare(PercentageBox o1, PercentageBox o2) {
        return o1.mCountry.mNaturalResistance 
          < o2.mCountry.mNaturalResistance ? -1 : 
             o1.mCountry.mNaturalResistance > o2.mCountry.mNaturalResistance ? 1 : 0;
    }
});

谁能让我知道我要去哪里错了?

4

1 回答 1

6

您的代码完美运行:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Snippet {

    static class Country {

        float mNaturalResistance;
    }

    static class PercentageBox {

        Country mCountry = new Country();
    }

    public static void main(final String[] args) {
        List< PercentageBox > mNaturalResistanceBoxes = new ArrayList< Snippet.PercentageBox >();
        for (int i = 0; i < 4; i++) {
            mNaturalResistanceBoxes.add(new PercentageBox());
        }

        mNaturalResistanceBoxes.get(0).mCountry.mNaturalResistance = 3.3f;
        mNaturalResistanceBoxes.get(1).mCountry.mNaturalResistance = 2.2f;
        mNaturalResistanceBoxes.get(2).mCountry.mNaturalResistance = 4.4f;
        mNaturalResistanceBoxes.get(3).mCountry.mNaturalResistance = 1.1f;

        Collections.sort(mNaturalResistanceBoxes, new Comparator< PercentageBox >() {

            @Override
            public int compare(final PercentageBox o1, final PercentageBox o2) {
                return o1.mCountry.mNaturalResistance < o2.mCountry.mNaturalResistance ? -1
                    : o1.mCountry.mNaturalResistance > o2.mCountry.mNaturalResistance ? 1 : 0;
            }
        });

        for (PercentageBox box : mNaturalResistanceBoxes) {
            System.out.println(box.mCountry.mNaturalResistance);
        }
    }
}

输出:

1.1
2.2
3.3
4.4
于 2013-04-17T13:30:33.693 回答