簡體   English   中英

檢查一個 ArrayList 是否包含與另一個 ArrayList 相同的元素

[英]Check if an ArrayList contains the same element as another ArrayList

我使用了其他一些答案來解決我的問題。 但我想知道是否有辦法進一步改善這一點?

// Copy the masterList ArrayList and then sort in ascending order and then make a third 
// ArrayList and loop through to add the 8 lowest values to this list.
ArrayList<Integer> sortedList = new ArrayList<>(Calculator.masterList);
Collections.sort(sortedList);
ArrayList<Integer> lowEight = new ArrayList<>();
for (int i = 0; i < 8; i++) {
    lowEight.add(sortedList.get(i));
}
// Set TextView as the value of index 0 in masterList ArrayList, check if lowEight 
// ArrayList contains the element that is the same as masterList index 0 and if
// so highlight s1 textview green.
s1.setText("Score 1 is " + String.format("%d", Calculator.masterList.get(0)));
if (lowEight.contains(Calculator.masterList.get(0))) {
    s1.setBackgroundColor(Color.GREEN);
}

這通過突出顯示是在兩個值工作的程度masterListlowEight但例如如果數字7是lowEight並顯示在9倍masterList它將突出顯示所有9個OCCURENCES。 有沒有辦法將確切的對象從masterList移動到sortedList ,然后移動到lowEight ,然后是一種檢查對象而不僅僅是值的方法?

讓我提供一個更簡潔的示例來說明您的要求。 讓我們使用以下代碼:

ArrayList<Integer> list1 = new ArrayList<Integer>() {
    {
        add(5);
        add(5);
    }
};

ArrayList<Integer> list2 = new ArrayList<>();
list2.add(list1.get(0));
list1.forEach((i) -> System.out.println(list2.contains(i)));

輸出是:

true
true

但你會期望它是:

true
false

因為第一個和第二個元素是不同的對象。 這里的問題是,雖然它們是不同的對象,但它們是相同的對象。 Integer 類是用 Java 編寫的,如果它們表示相同的值,則任何 Integer 都等於另一個 Integer。 當您運行contains()方法時,它會看到該列表確實包含一個與您提供的對象相同的對象(在這種情況下,它們都表示值 5),因此它返回 true。 那么我們如何解決這個問題呢? 我們如何區分一個 Integer 對象和另一個? 我會寫你自己的“整數”類。 像“MyInteger”這樣的東西。 這是您可以使用的一個非常簡單的實現:

public class MyInteger {
    private final int i;

    public MyInteger(int i) {
        this.i = i;
    }

    public int toInt() {
        return i;
    }
}

然后當我們在 ArrayList 代碼中使用它時:

ArrayList<MyInteger> list1 = new ArrayList<MyInteger>() {
    {
        add(new MyInteger(5));
        add(new MyInteger(5));
    }
};

ArrayList<MyInteger> list2 = new ArrayList<>();
list2.add(list1.get(0));
list1.forEach((i) -> System.out.println(list2.contains(i)));

我們得到我們的預期輸出:

true
false

這是有效的,因為我們的新 MyInteger 類隱式使用默認的equals()方法,該方法總是返回 false。 換句話說,沒有兩個 MyInteger 對象永遠相等。 您可以將同樣的原則應用到您的代碼中。

暫無
暫無

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

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