繁体   English   中英

您可以实现并重写list.sort()方法来对有理数列表进行排序吗?

[英]Can you implement and override the list.sort() method to sort a list of rational numbers?

因此,我遇到了以下问题:

编写一个程序,该程序创建一个“理性列表”并将其按升序排序。 使用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;
}

抱歉,有点长。 所以我的想法是创建一个排序方法,并使用compareTo方法来确定Rational是否在正确的位置,如果不交换的话。 但是然后我不确定您是否能够像在数组中一样移动列表中的元素。 所以我以为也许我需要实现Collections.sort()方法并覆盖sort方法,但是我遇到了同样的问题。 也许我可以使用.toArray?

有人可以阐明这样做的方式吗? 只是提示会很有用。

由于您实现了可比性,因此Collections.sort(rationals)将起作用。

这是因为Collections.sort将可用于任何可比较事物列表。 它已被设计为使用您定义的Comparable.compareTo()方法,并且只要正确实现了compareTo,它就应该对列表进行排序。

您在做什么大致正确。

但是然后我不确定您是否能够像在数组中一样移动列表中的元素。

在后台, Collections.sort方法可以将列表的元素复制到数组中,对数组进行排序,然后从排序后的数组中重建列表。 实际行为取决于列表实现类。

在应用程序的主要方法中,应该创建一个Rational列表,然后使用Collections.sort()方法。

您应该生成Rational的随机列表,然后使用Collection.sort(rationalsList);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM