[英]Sorting array objects Java
對於此作業,我們將創建一個不大於10且其元素為Animal類型的數組(Animal是我們必須創建的對象)。 提示用戶輸入有關動物的信息(名稱,手臂,腿的數量),並將該信息存儲到陣列的每個動物對象中。
然后,該程序應該計算四肢的總數,並根據計算出的數目從最大到最小對數組進行排序。
這是代碼:
public static void sortArray (Array [] name)
{
// This method will take in the array and sort it based
// on the number of limbs from greatest to least.
int maxLimbs = 0;
for (int j = 0; j < name.length; j++) {
int limbValue = name[i].getNumberOfLimbs();
if (limbValue > maxLimbs) {
maxLimbs = limbValue;
// Store the max value in the first position
name[0] = name[i];
}
}
}
我知道這是在尋找最大值並將其放在第一位,但是我正在努力使它排序其余元素。 關於如何解決此問題的任何建議,它將對整個數組進行排序並按從大到小的順序排序?
還是已經有一種排序方法可用於以對象為對象的數組? 我對此並不陌生,因此我仍在嘗試掌握一些概念。 感謝您的幫助。
您可以使用Arrays.sort方法
public static <T> void sort(T[] a, Comparator<? super T> c)
您應該給它一個數組和一個比較器,該比較器知道如何比較兩個動物對象
或者你可以使用
public static void sort(Object[] a)
這需要您的元素的類實現Comparable接口
public class SortAnimals {
public static void main(String[] args) {
Animals[] animals = new Animals[3];
animals[0] = new Animals("Animal1",0,4);
animals[1] = new Animals("Animal2",2,6);
animals[2] = new Animals("Animal3",1,1);
Arrays.sort(animals,Collections.reverseOrder());
for (int i = 0; i < animals.length; i++) {
Animals animals2 = animals[i];
System.out.println(animals2);
}
}
}
class Animals implements Comparable<Animals>{
private String name;
private int hands;
private int legs;
//getters and setters omitted for brevity
Animals(String name, int hands, int legs){
this.name = name;
this.hands = hands;
this.legs = legs;
}
@Override
public int compareTo(Animals o) {
int totalLimbs = this.hands + this.legs;
return totalLimbs - (o.hands + o.legs);
}
@Override
public String toString() {
return "Animals [name=" + name + ", hands=" + hands + ", legs=" + legs
+ "]";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.