我寫了一個Predicate
代碼,花費下列條件Object
,並測試其:謂詞泛型方法
- 如果
Object
類型爲String
,包含"k"
那麼它應該返回true。 - 如果
Object
類型是Integer
並且大於100
那麼它應該返回true。 - 如果
Object
類型是Employee
這是班級,並且員工的工資大於60000
,它應該返回true。
書面Predicate
方法我寫的remove
方法,根據Predicate
方法去除列表中的值之後。
public class ConditionalRemove {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>(Arrays.asList("ramesh", "kushal", "suresh", "kc"));
System.out.println(conditionalRemove(list));
}
public static <T> List<T> conditionalRemove(ArrayList<T> list) {
ConditionCheck<T> cond = new ConditionCheck<>();
for (T t : list) {
if (cond.test(t)) {
list.remove(t);
}
}
return list;
}
static class ConditionCheck<T> implements Predicate<T> {
@Override
public boolean test(T t) {
if (t instanceof String) {
return (((String) t).contains("k"));
} else if (t instanceof Integer) {
return ((int) t > 100);
} else if (t instanceof Employee) {
return ((int) ((Employee) t).getSalary() < 60000);
}
return true;
}
}
}
編譯此代碼後,我發現Exception in thread "main" java.util.ConcurrentModificationException
您從列表中,而你迭代它(在'conditionalRemove()'要修復刪除,使列表的副本,並重復說 – nbokmans
@nbokmans - 沒必要 - 只需使用迭代明確。 –
可能重複[迭代通過哈集合,避免ConcurrentModificationException當在循環中刪除](http://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re) –