2 oiu1010110 oiu1010110 于 2016.04.23 13:22 提问

java 集合排序问题,谢谢指导。

有一串分数我存在了rationalList集合里,然后要求对分数按倒数大小对分数进行排序
ListrationalList = new ArrayList<>();
Collections.sort(rationalList,new InverseComparator());
public class InverseComparator implements Comparator {
// 比较两个分数倒数的大小
@Override
public int compare(Rational obj1, Rational obj2) {
Rational ra1 = obj1;
Rational ra2 = obj2;
int nm1 = obj1.getNumerator();
int dm1 = obj1.getDenominator();
ra1.setDenominator(nm1);
ra1.setNumerator(dm1);

    int nm2 = obj2.getNumerator();
    int dm2 = obj2.getDenominator();
    ra2.setDenominator(nm2);
    ra2.setNumerator(dm2);  这里这样的话就改变了原来的分数,后面输出来的都是倒数,而不是原来的分数,怎么写呢要?
    //……
}
}

3个回答

oiu1010110
oiu1010110   2016.04.23 19:58
已采纳

public int compare(Rational obj1, Rational obj2) {

    int nm1 = obj1.getNumerator();
    int dm1 = obj1.getDenominator();
    Rational ra1 = null;
    try {
        ra1 = new Rational(dm1,nm1);
    } catch (IllegalRationalException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    int nm2 = obj2.getNumerator();
    int dm2 = obj2.getDenominator();
    Rational ra2 = null;
    try {
        ra2 = new Rational(dm2,nm2);
    } catch (IllegalRationalException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //……这里用前面本身排序的compareTo();只是参数换成了两个比较
    }



    //已解决
CSDNXIAOD
CSDNXIAOD   2016.04.23 13:32

java集合排序问题
Java集合中的排序问题
Java集合中的排序问题
----------------------biu~biu~biu~~~在下问答机器人小D,这是我依靠自己的聪明才智给出的答案,如果不正确,你来咬我啊!

molashaonian
molashaonian   2016.04.23 15:15

继承Comparable接口,自己写排序方法
class Name implements Comparable{

public String firstName,lastName;

public Name(String firstName,String lastName){

this.firstName=firstName;

this.lastName=lastName;

}

public int compareTo(Name o) { //实现接口

int lastCmp=lastName.compareTo(o.lastName);

return (lastCmp!=0?lastCmp:firstName.compareTo(o.firstName));

}

public String toString(){ //便于输出测试

return firstName+" "+lastName;

}

}

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!