2015-11-17 79 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; 
}