2015-05-20 46 views
1

這是我的代碼是否可以從包含自定義類型的元素的List中移除重複項?

package com.dto; 

public class OtherBrands { 

    private String otherbrandsname ; 
    public String getOtherbrandsname() { 
     return otherbrandsname; 
    } 
    public void setOtherbrandsname(String otherbrandsname) { 
     this.otherbrandsname = otherbrandsname; 
    } 
    public String getDealerBrandQty() { 
     return dealerBrandQty; 
    } 
    public void setDealerBrandQty(String dealerBrandQty) { 
     this.dealerBrandQty = dealerBrandQty; 
    } 
    private String dealerBrandQty ; 

} 

import java.util.ArrayList; 
import java.util.List; 
import com.dto.OtherBrands; 

public class Test { 
    public static void main(String args[]) 
    { 
     List <OtherBrands> otherBrandsList = new ArrayList <OtherBrands>(); 
     for (int k = 0; k < 3; k++) { 
      OtherBrands otherbrands = new OtherBrands(); 
      String otherbrandsname = "Test"; 
      String dealerBrandQty = "2"; 
      otherbrands.setOtherbrandsname(otherbrandsname); 
      otherbrands.setDealerBrandQty(dealerBrandQty); 
      otherBrandsList.add(otherbrands); 
     } 

     for(int i=0;i<otherBrandsList.size();i++) 
     { 
      System.out.println(otherBrandsList.get(i).getOtherbrandsname()+"\t"+otherBrandsList.get(i).getDealerBrandQty()); 

     } 
    } 
} 

當我運行這個程序,結果是:

Test 2 
Test 2 
Test 2 

如果鍵和值是相同的,它應該被視爲重複

是否可以從列表中刪除重複項?

+1

您可以使用'set'代替,並且在您的dto中請記住重寫'hashCode()'和'equals()'方法。 – Kartic

+0

你用'Map'類型嘗試過嗎? –

+0

在將元素添加到'list'時,您可以檢查新元素是否已經存在。這可以通過重寫'hashCode()'和'equals()'方法來完成。這可以通過'HashSet'來完成,你也需要重寫這兩種方法。閱讀這些方法的合同規則 – Prashant

回答

4

首先,如果您想避免重複,請使用HashSet而不是List。

其次,您必須覆蓋hashCodeequals,以便HashSet知道您認爲哪些元素彼此相等。

public class OtherBrands { 

    @Override 
    public boolean equals (Object other) 
    { 
     if (!(other instanceof OtherBrands)) 
      return false; 
     OtherBrands ob = (OtherBrands) other; 
     // add some checks here to handle any of the properties being null 
     return otherbrandsname.equals(ob.otherbrandsname) && 
       dealerBrandQty.equals(ob.dealerBrandQty); 
    } 

    @Override 
    public int hashCode() 
    { 
     return Arrays.hashCode(new String[]{dealerBrandQty,otherbrandsname}); 
    } 
} 
+0

我不能使用Hashset,因爲同名可以出現兩次,具有不同的數量。 – Pawan

+1

根據'name'和'quantity'定義您的equals方法。根據你所說的重複,你有一些標準是正確的。以相同的方式實施您的等同方法。 – Kartic

+0

@PreethiJain你可以使用HashSet,如果你定義兩個對象相同,如果他們有相同的名字和相同的數量 – Eran

1

您應該使用HashSet代替ArrayList,因爲它保證刪除重複項。它只需要您在OtherBrands類中實施hashCode()equals()方法。作爲提示,如果您使用Eclipse:您可以使用編輯器菜單功能'Source/Generate HashCode and Equals'生成兩種方法。然後選擇所有屬性,這些屬性定義了OtherBrands項目(名稱,數量)的標識。

+0

我仍然可以使用hashset? \t 相同名稱可以出現兩次不同數量。 – Pawan

+0

是的,你可以,但這取決於hashCode()和equals()的實現,因爲這些方法確定HashSet的身份。 –

相關問題