簡體   English   中英

Java compareTo 數組排序

[英]Java compareTo array sort

我有兩個類MainObject 我需要根據其值按升序對數組中的對象進行排序。 我從 compareTo 返回 -1、1 和 0,我需要相應地運行 for 循環來對數組進行排序。 我不想使用 Arrays.sort,我需要手動進行。 Main類中的排序部分不起作用。 任何幫助都可能有用。 謝謝你。

public class Main {

public static void main(String[] args) {

    Object[] arr = new Object[6];

    arr[0] = new Object(2);
    arr[1] = new Object(5);
    arr[2] = new Object(3);
    arr[3] = new Object(1);
    arr[4] = new Object(6);
    arr[5] = new Object(4);

    System.out.println("List of instances");
    for (int i = 0; i < 5; i++) {
        System.out.println(arr[i].getValue());
    }

    System.out.println();

    Object tempVar;

    for (int i = 0; i < arr.length; i++) {

        for (int j = 0; j < 5; j++) {

            int result = arr[i].compareTo(arr[i]);

            if (result == -1) {
                tempVar = arr[j + 1];
                arr[j + 1] = arr[i];
                arr[i] = tempVar;
            }
        }
    }

    System.out.println("List of sorted instances");
    for (int i = 0; i < arr.length; i++) {
        System.out.println(arr[i].getValue());
    }

}

}

public class Object implements Comparable<Object> {

private int value;

public Object(int value) {
    this.value = value;
}

public int getValue() {
    return value;
}

public void setValue(int value) {
    this.value = value;
}

@Override
public int compareTo(Object o) {
    int result = 0;

    if (this.value > o.getValue()) {
        result = 1;
    } else if (this.value < o.getValue()) {
        result = -1;
    } else if (this.value == o.getValue()) {
        result = 0;
    }

    return result;
}

}

如果要循環遍歷集合的所有元素,請不要使用固定值,例如此處的5

System.out.println("List of instances");
for (int i = 0; i < 5; i++) {

使用arr.length代替。

這也適用於這一行:

for (int j = 0; j < 5; j++) {

5 可能是正確的,因為數組長度是6並且您想在最后一個索引之前終止,但是如果您使用更大的數組,此代碼將中斷。 使用arr.length - 1而不是5


此行將數組元素與其自身進行比較:

int result = arr[i].compareTo(arr[i]);

因此result將始終為0 將其更改為:

int result = arr[i].compareTo(arr[j]);

或者:

int result = arr[j].compareTo(arr[i]);

嘗試這兩種方法以查看它們之間的區別。


在上面的修復中,您正在比較索引ij上的元素。 因此,您應該更改此代碼:

if (result == -1) {
    tempVar = arr[j + 1];
    arr[j + 1] = arr[i];
    arr[i] = tempVar;
}

使用正確的j索引:

if (result == -1) {
    tempVar = arr[j];
    arr[j] = arr[i];
    arr[i] = tempVar;
}

您當前的代碼比較ij的元素(好吧,不是j由於錯誤,而是您的意思),但是由於不同的索引j+1交換不同的元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM