2009-05-06 46 views
2

Apache Commons Collections有沒有辦法讓PredicatedList(或類似的)在你試圖添加的東西不符合謂詞時不拋出IllegalArgumentException?如果不匹配,它會忽略將項目添加到列表中的請求。Apache commons PredicatedList沒有IllegalArgumentException

因此,舉例來說,如果我這樣做:

List predicatedList = ListUtils.predicatedList(new ArrayList(), PredicateUtils.notNullPredicate()); 
... 
predicatedList.add(null); // throws an IllegalArgumentException 

我希望能夠做到以上,但隨着空的加入沒有拋出的異常被忽略。

如果Commons Collections支持這個,我無法從JavaDocs中找出答案。如果可能的話,我想這樣做,而無需滾動我自己的代碼。

+0

這不就是一個謂詞列表中的一點嗎,您只希望列表中的某些東西符合爲其定義的條件嗎? 爲什麼不使用普通列表? – 2009-05-06 13:00:28

+0

是的,這是一個預測列表的重點。但是我希望它可以忽略與謂詞不匹配的事物,即進行謂詞檢查,但如果不匹配則不要抱怨。 – 2009-05-06 13:02:04

回答

0

剛剛發現CollectionUtils.filter。我可能可以重寫我的代碼來使用它,雖然它仍然會很好地安靜地阻止首先添加到列表中。

List l = new ArrayList(); 
    l.add("A"); 
    l.add(null); 
    l.add("B"); 
    l.add(null); 
    l.add("C"); 

    System.out.println(l); // Outputs [A, null, B, null, C] 

    CollectionUtils.filter(l, PredicateUtils.notNullPredicate()); 

    System.out.println(l); // Outputs [A, B, C] 
1

難道你不能只是吞下異常?

try 
{ 
    predicatedList.add(null); 
} 
catch(IllegalArgumentException e) 
{ 
    //ignore the exception 
} 

你會probablly需要編寫一個包裝來爲你做這個...

相關問題