2015-11-17 78 views
-6

我有問題從這個方法返回ArrayList。該方法應該檢查給定的保險類型與存儲的保險類型。如果匹配,那麼該元素將被刪除,其餘的將被顯示。從方法返回ArrayList

請建議的語法,這裏返回數組列表

public ArrayList<Insurance> retrieveDetails(String insType){ 

    Iterator<Insurance> itr=insurancelist.iterator(); 

    while(itr.hasNext()) { 
    Insurance c=itr.next(); 

    if(c.getInsuranceType().equals(insType)) { 
    insurancelist.remove(c); 

} 
else 
    System.out.println(c); 


} 
+0

這甚至不會編譯 - 你有不平衡{} – NickJ

+0

你應該添加return語句 – Abdelhak

+0

u能請建議用於返回數組列表的語法 – Jason

回答

0

你看到的原因是:

[[email protected][email protected],com.Insurance @ 6d06d69c]

是保險類沒有toString()方法。所以它使用Object中默認的toString()方法。

public String toString() { 
    return getClass().getName() + "@" + Integer.toHexString(hashCode()); 
} 

如果你想讓它做一些更有意義,當你打印的保險對象,你要創建一個Insurance.java方法,看起來是這樣的,假設你有一個insuranceType字符串和策略ID值類變量:

public String toString() { 
    return this.policyID+": "+this.insuranceType; 
} 
0

假設這是你擁有的一切:

enum InsuranceType {} 

interface Insurance { 
    InsuranceType getType() 
} 

你這裏有兩個簡單的選擇: 1.使用它在列表中刪除元素,並隨時移除元素。 2.在列表中循環,找到要刪除的所有元素,然後在迭代後將其刪除。

public List<Insurance> retrieveDetais(List<Insurance> insurances, InsuranceType type) { 
    List<Insurance> toRemove = new ArrayList<Insurance>(); 
    for (Insurance i : insurances) { 
     if (i.getInsuranceType().equals(insuranceType)) { 
      toRemove.add(i); 
     } 
    } 
    for (Insurance i : toRemove) { 
     insurances.remove(i); 
    } 
    return insurances; 
} 

你總是可以讓這個更通用還是走迭代路線:

public List<Insurance> removeInsuranceType(List<Insurance> insurances, InsuranceType type) { 
    Iterator<Insurance> iter = insurances.iterator(); 
    while (iter.hasNext()) { 
     Insurance i = iter.next(); 
     if (i.getType() == type) { 
      iter.remove(); 
     } 
    } 
    return insurances; 
}