有一串分数我存在了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); //这里这样的话就改变了原来的分数,后面输出来的都是倒数,而不是原来的分数,怎么写呢要?
}
}
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();只是参数换成了两个比较
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。