1 16 package org.apache.commons.collections.collection; 17 18 import java.util.Collection ; 19 import java.util.Iterator ; 20 21 import org.apache.commons.collections.Predicate; 22 23 42 public class PredicatedCollection extends AbstractSerializableCollectionDecorator { 43 44 45 private static final long serialVersionUID = -5259182142076705162L; 46 47 48 protected final Predicate predicate; 49 50 62 public static Collection decorate(Collection coll, Predicate predicate) { 63 return new PredicatedCollection(coll, predicate); 64 } 65 66 78 protected PredicatedCollection(Collection coll, Predicate predicate) { 79 super(coll); 80 if (predicate == null) { 81 throw new IllegalArgumentException ("Predicate must not be null"); 82 } 83 this.predicate = predicate; 84 for (Iterator it = coll.iterator(); it.hasNext(); ) { 85 validate(it.next()); 86 } 87 } 88 89 98 protected void validate(Object object) { 99 if (predicate.evaluate(object) == false) { 100 throw new IllegalArgumentException ("Cannot add Object '" + object + "' - Predicate rejected it"); 101 } 102 } 103 104 113 public boolean add(Object object) { 114 validate(object); 115 return getCollection().add(object); 116 } 117 118 127 public boolean addAll(Collection coll) { 128 for (Iterator it = coll.iterator(); it.hasNext(); ) { 129 validate(it.next()); 130 } 131 return getCollection().addAll(coll); 132 } 133 134 } 135 | Popular Tags |