簡體   English   中英

如何在Java中使用removeall()減去ArrayList?

[英]how to subtract ArrayList using removeall() in java?

我在Java中有數組列表:

List<Correction> Auv=new ArrayList<>();
List<Correction> Produv=new ArrayList<>();

然后我想用Auv減去Produv的值,這是一個例子:

Produv.add(new Correction("a","b"));
Produv.add(new Correction("a","c"));
Produv.add(new Correction("b","d"));
Produv.add(new Correction("b","c"));

Auv.add(new Correction("c","a"));
Auv.add(new Correction("b","c"));

Produv.removeall(Auv);

但是沒有減去任何東西,數組仍然包含它的初始值,有什么辦法嗎? 我嘗試覆蓋equals(),仍然得到相同的結果

這里是我的改正類的代碼:

    public class Correction {
    private String node0;
    private String node1;

    public Correction(String node0, String node1) {
        this.node0 = node0;
        this.node1 = node1;
    }

    public void setNode0(String node0){
        this.node0=node0;
    }
    public void setNode1(String node1){
        this.node1=node1;
    }

    public String getNode0(){
        return node0;
    }
    public String getNode1(){
        return node1;
    }

    @Override
    public boolean equals(Object object){
        boolean same = false;

        if (object != null && object instanceof Correction)
        {
            same = this.node0 == ((Correction) object).node1 && this.node1 == ((Correction) object).node1;
        }

        return same;
    }
}

解決了!! 這只是在重寫equals()方法(感謝伙計們)時出現的錯誤,這里是我的修正:

   @Override
    public boolean equals(Object object){
        boolean same = false;

        if (object != null && object instanceof Correction)
        {
            same = (this.node0 == ((Correction) object).node1 && this.node1 == ((Correction) object).node0)||(this.node0 == ((Correction) object).node0 && this.node1 == ((Correction) object).node1);
        }

        return same;
    }

您的equals方法看起來不對。 比較this.node0((Correction) object).node0更有意義。

我認為應該是:

public boolean equals(Object object){
    boolean same = false;

    if (object != null && object instanceof Correction)
    {
        same = this.node0.equals(((Correction) object).node0) && this.node1.equals(((Correction) object).node1);
    }

    return same;
}

另外,這是錯字嗎?

Auv.add("c","a");
Auv.add("b","c");

可能應該是:

Auv.add(new Correction ("c","a"));
Auv.add(new Correction ("b","c"));

暫無
暫無

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

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