EDIT:配列オブジェクトを "カロリー"でソートしようとしています。どのように私は比較可能なインターフェイスを介してオブジェクトの配列を並べ替えるのですか?
現在、タスクの1つがソートされた配列を出力するという課題に取り組んでいます。
私の知る限り、私の配列をソートできなかったのは、同等のインターフェースを介して解決することができます。次に、java.util.Arrays.sort(/ varをここでソートする /)メソッドを使用して配列をソートすることができます。
私は単に別のループを書くことができますが、それは達成しようとしているものではありません。アイデア?
ありがとうございます。
ソースコード:Comparable
を実装
import java.util.Arrays;
public class Food implements Comparable<Food>
{
public static void main(String[] args)
{
int n = 5;
Food f1 = new Food(TYPES[1], 300);
Food f2 = new Food(TYPES[2], 400);
System.out.println(Arrays.toString(createSortedRandomList(n)));
System.out.println("f1 calories: " + f1.getCalories());
System.out.println("f1 type: " + f1.getType());
System.out.println("f2 calories: " + f2.getCalories());
System.out.println("f2 type: " + f2.getType());
System.out.println();
System.out.println(f1.compareTo(f2));
}
private static final String[] TYPES = {"Apple", "Pear", "Cookie"};
private String type;
private int calories;
public Food(String type, int calories)
{
this.type = type;
this.calories = calories;
}
public String toString()
{
String foodString = "Type:" + getType() + " Calories:" + getCalories();
return foodString;
}
public String getType()
{
return type;
}
public int getCalories()
{
return calories;
}
public static Food[] createSortedRandomList(int n)
{
Food[] food = new Food[n];
int i;
for(i = 0; i < n; i++)
{
food[i] = new Food(TYPES[(int)(3.0*Math.random())], (int)(501 * Math.random())); // 0 <= calories <= 500
}
Arrays.sort(calories); // incorrect code here **************************************************************
return food;
// TODO: create a list with n random instances and sort them
}
public int compareTo(Food o)
{
if (this == o)
{
return 0;
}
if (this.type.length()*this.calories < o.type.length()*this.calories)
{
return -1;
}
else
{
return 1;
}
}
}
奇妙なソート機構が実際にタスクに指定されたので、私はそれがcompareToメソッドにおける基準は、実際の基準によってであることを意味していると考えています配列をソートする必要があります。 この場合、私のソートされた配列が私に間違った出力を与える理由を理解する必要があります。例:出力: [タイプ:クッキーカロリー:378、タイプ:クッキーカロリー:178、タイプ:梨カロリー:231、タイプ:梨カロリー:209、タイプ:梨カロリー:467] –
私はcompareToメソッド私はエラーが発生したことを認識した。この質問を投稿する前に、私はcompareToメソッドが実際にソートを行っていたことを知らなかった。あなたの説明は私の仕事に必要なものを理解するのに役立ちました。 –