2013-06-01 63 views
1

我是一個Java新手..但我相信我可以以高效的方式完成這項工作。添加到數組列表

此方法的目的是添加具有唯一標識的產品。如果我的產品重複,我應該拋出異常。那麼,這個序列不適用於多線程環境。

public void addProduct(Product product) 
     throws ProductAlreadyExistsException { 
    product.id = ++nextId; 
    this.id = product.id; 

    Iterator<Product> it = allProducts.iterator(); 
    Product p= null; 

    boolean flag= false; 
    if (!allProducts.isEmpty()) { 
     while(it.hasNext()){ 
      p= it.next(); 
      if (p.getName() == product.getName()) 
       throw new ProductAlreadyExistsException(p.getName()); 
      else 
       flag = true; 
     } 

    } 
    else 
     allProducts.add(product.id-1, product); 

    if(flag){ 
     allProducts.add(product.id-1, product); 
    } 
} 

我想要的是這樣的。

for (Product p : allProducts) { 
     if (p.getName() == product.getName()) { 
      throw new ProductAlreadyExistsException(p.getName()); 
     } 
      allProducts.add(p); 
     } 
} 

這是行不通的。 感謝指導我..

回答

3

在Java中,您使用s1.equals(s2)方法來確定兩個字符串是否相等。

if (p.getName() == product.getName()) // This will always return false, because references are compared here 

你應該做的是:

if (p.getName().equals(product.getName())) 

注:我假設getName()返回一個字符串。

+0

在Product中實現equals()方法好得多,所以它們可以將自己與其他對象進行比較。在這樣做的時候,還要記得實現hashCode。 IDE可以爲你自動生成這兩種方法。關於equals和hashCode合約,請閱讀[this](http://www.coderanch.com/t/269905/java-programmer-SCJP/certification/hashcode-equals-contract)。 – LexLythius

+0

我做了上述改變,它效果更好。非常感謝 – Newbie

3

一般情況下,沒有授予任何類型的List將包含唯一的要素保障,但我想你不必去通過創建Iterator的過程。

僅僅使用List.contains()就足夠了 - 如果列表不包含該元素,則將其添加,否則拋出異常*。

public void addProduct(Product theProduct) throws ProductAlreadyExistsException { 
    if(allProducts.contains(theProduct)) { 
     throw new ProductAlreadyExistsException("Not unique!"); 
    } 
    allProducts.add(theProduct); 
} 

*:拋出異常是有點傻海事組織。這隻應該保留給真正的特殊行爲。相反,你可能更喜歡Set

+0

Appart知道沒有重複項,Set對查找也會更有效率。 – LexLythius

+0

不幸的是,ID沒有得到創建.. Id是空的..我應該改變構造函數。我在構造器中有以下代碼。 \t public Product(String name,double price,DeptCode code){ \t \t this(null,name,price,code); \t} \t公共產品(整數ID字符串名稱,價格雙,代碼DEPTCODE){ \t \t this.id = ID; \t \t這個。name = name; \t \t this.price = price; \t \t this.dept = code; – Newbie

+0

不管ID是否被綁定到'Product'對象? – Makoto

0

誠的回答是一個簡單的方法,以確保對象處於一個獨特的List

另外,你需要確保實現equals(Object obj)方法的類的對象的,要添加到列表中。該List.contains()方法包含每個對象上調用equals(yourObject)返回true,只要equals(yourObject)返回true,任何在List對象。

在這裏你可以看到一個很好的實現equals(Object obj),你可以在你的Product課堂上使用。

public class Product { 
    //Other methods here 
    public boolean equals(Object obj) { 
     if(this == obj) 
      return true; 
     if(obj == null) 
      return false; 
     if(this.getClass() != obj.getClass()) 
      return false; 
     Product product = (Product)obj; 
     boolean result = true; 
     //Compare fields of this with fields of product and set result 
     return result; 
    } 
} 
+0

我會嘗試這個實現..謝謝.. – Newbie