[英]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.