所以我遇到了以下问题:
编写一个创建Rationals列表的程序,并将它们分类为增加 订购。使用Collections Framework类中的适当方法进行排序 元素逐渐增加。
我创造了一个理性的'用来表示有理数的类,我也列出了随机有理数。但是我在找出实现排序列表方法的方法时遇到了麻烦。在我继续之前,这里是代码的示例:
public class Rational implements Comparable<Rational> {
private int num;
private int denom;
private int common;
// Default constructor initialises fields
public Rational() throws IllegalNumDenomException {
setNum(1);
setDenom(2);
}
// Constructor sets fields with given parameters
public Rational(int num, int denom) throws IllegalNumDenomException {
common = gcd(num,denom);
setNum(num/common);
setDenom(denom/common);
}
//Compares two rational numbers
public int compareTo(Rational rhs) {
int tempNumerator = this.getNum() * rhs.getDenom();
int tempNumeratorRhs = rhs.getNum() * this.getDenom();
//Compares rationalised numerators and returns a corresponding value
if (tempNumerator < tempNumeratorRhs) {
return -1;
} else if (tempNumerator > tempNumeratorRhs) {
return 1;
}
return 0;
}
// Overriden toString method
public String toString() {
return num + "/" + denom;
}
//Calculates the GCD of a fraction to simplify it later on
public int gcd(int x, int y) throws IllegalNumDenomException{
while(x != 1){ //Prevents infinite loop as everything is divisible by 1
if(x == y){
return x;
}
else if(x>y){
return gcd(x-y,y);
}
return gcd(x,y/x);
}
return 1;
}
public class RationalList {
public static void main(String[] args) throws IllegalNumDenomException {
List<Rational> rationals = new ArrayList<Rational>();
Random rand = new Random();
int n = rand.nextInt(50) + 1;
//Generates 9 random Rationals
for(int i = 1; i<10; i++){
rationals.add(new Rational(i,n));
n = rand.nextInt(50) + 1;
}
System.out.println("Original Order: " + rationals.toString());
sort(rationals);
System.out.println(rationals);
}
public static List<Rational> sort(List<Rational> rationals){
//Use compareTo method inside a loop until list is sorted
return rationals;
}
对不起它有点长。所以我的想法是创建一个sort方法并使用compareTo方法来确定Rational是否在正确的位置,如果不交换它。但是,我不确定你是否能够像在数组中那样在列表中移动元素。所以我想也许我需要实现Collections.sort()方法并覆盖排序方法,但我遇到了同样的问题。也许我可以使用.toArray?
任何人都可以对如何做到这一点有所了解吗?只是提示会很有用。
答案 0 :(得分:1)
由于您实现了可比较,因此Collections.sort(有效性)将起作用。
这是因为Collections.sort可以处理任何可比较的事物列表。它已被设计为使用您已定义的Comparable.compareTo()方法,并且只要您的compareTo正确实现,它应该对您的列表进行排序。
答案 1 :(得分:1)
你在做什么大致是正确的。
但是我不确定你是否能够像在数组中那样在列表中移动元素。
引擎盖下,Collections.sort
方法可以将列表的元素复制到数组中,对数组进行排序,然后从排序的数组中重建列表。实际行为取决于列表实现类。
答案 2 :(得分:0)
在应用程序的main方法中,您应该创建一个Rational列表,然后使用Collections.sort()方法。
您应该生成Rational的随机列表,然后使用Collection.sort(rationalsList);