2017-10-09 54 views
1

我在jsf中有數據表。點擊添加按鈕後,根據選定的值加載列表。元素成功添加到列表中。 添加到列表中,Arraylist刪除第一次發生,而不是確切的對象

public class CompanyProduct implements Serializable{ 
    private static final long serialVersionUID = 1L; 

     @Id 
     @GeneratedValue 
     @Getter @Setter private int id; 

     @ManyToOne 
     @JoinColumn(name = "productId", referencedColumnName = "id") 
     @Getter @Setter private Product product; 

     @ManyToOne 
     @JoinColumn(name = "companyId", referencedColumnName = "id") 
     @Getter @Setter private Company company; 

     @Setter @Getter private Double price; 

     @Setter @Getter private Double sellingprice; 

     @Column 
     @Getter @Setter private Integer minQuantity; 

     @Column 
     @Getter @Setter private Integer maxQuantity; 

     @Column 
     @Getter @Setter private Integer leadTime; 

     @ManyToOne 
     @JoinColumn(name="uom_group_item_id") 
     @Getter @Setter private UomGroupItem uomGroupItem; 

} 

public void addToAssociation() { 


     List<CompanyProduct> tmpList = new ArrayList<CompanyProduct>(companyproducts); 

     for (Product p : selectedProducts) { 
      boolean flag = false; 

      for(CompanyProduct companyProduct: tmpList){ 
       if(companyProduct.getUomGroupItem() == null && companyProduct.getProduct() != null && companyProduct.getProduct().getId().equals(p.getId())){ 
        flag = true; 
       } 
      } 

      if(!flag){ 
       addCompanyProducts(p, null); 
      } 

      addUomGroupProduct(p); 
     } 
     selectedProducts = null; 
     loadLazyProducts(); 
    } 

private void addCompanyProducts(Product p,UomGroupItem item){ 
     CompanyProduct sg = new CompanyProduct(); 
     sg.setProduct(p); 
     sg.setCompany(company); 
     sg.setPrice((double) (p.getMrp()==null?0f:p.getMrp())); 
     sg.setSellingprice((double) (p.getMrp()==null?0f:p.getMrp())); 

     if(item != null){ 
      sg.setUomGroupItem(item); 
     } 

     companyproducts.add(sg); 
    } 

,但問題是,當我去刪除,這樣操作,

for (CompanyProduct sg : selectedToBeAssociatedProducts) { 
     companyproducts.remove(sg); 
    } 

但在列表中刪除它第一次出現。所以我可以知道這個問題的原因。提前致謝。

請讓我知道,如果有任何疑問。

+0

在刪除操作添加更多的代碼,比如什麼是對象 –

+1

的內容你是否覆蓋你的對象的'equals'方法? –

+0

@SachinGupta添加了更多代碼。我沒有做任何事情只是傳遞對象。 – Balasubramanian

回答

0

如果您想要刪除列表中的第一項。是否list.remove(0)

如果您想刪除列表中對應於特定值的第一項。不要list.remove(value)

+0

實際上我只想刪除確切的對象,而不是第一次出現。 pl檢查編輯的問題 – Balasubramanian

1

這是由設計,請參閱列表API

remove(Object o) 

Removes the first occurrence of the specified element from this list, if it is present (optional operation). 

如果要刪除所有出現使用List.removeAll,這樣

list.removeAll(Collectoins.singelton(obj); 
+0

請找到編輯的問題爲你的參考。我想刪除確切的對象 – Balasubramanian

2
  • List.removeAll(Object value)將刪除的每次出現值
  • List.remove(Object value)將刪除首次出現的值
  • List.remove(int position)將移除位置上的值
1

請嘗試以下一段代碼。如果它不起作用。請告訴我們爲什麼。要不接受的答案,關閉這個問題

list.removeAll(Collectoins.singelton(obj);