所以,我一直在考慮以下問題:您可以實現並重寫list.sort()方法來對有理數列表進行排序嗎?
編寫創建有理數的名單,並將其分類成增加 順序的程序。使用集合框架類中的適當方法將元素按遞增順序排序。
我創建了一個'Rational'類來表示有理數,並且我還創建了隨機Rational數的列表。但是我很難找出實現列表排序方法的方法。這裏是我繼續前進的代碼示例:
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()方法並重寫排序方法,但我遇到了同樣的問題。也許我可以使用.toArray?
任何人都可以在如何做到這一點上點亮一下嗎?只是提示會很有用。
如果你已經實現了'Comparable'得當,你不需要重寫任何代碼排序 - 你應該能夠調用'集合。排序(有理數)'。 –
這是過分複雜的事情。調用'Collections.sort(合理)'。沒有必要重新實現,重寫或其他任何東西。 –
替代方法是'list.sort(Comparator.naturalOrder())'(或者,uglier,'list.sort(null)':這就是'Collections.sort()'的實現,BTW) –