Guava Constraint非常有用。有它,我们可以创建一些受限的容器,如list/set/multiset/map... 看看代码实例。 import java.util.HashSet; import java.util.Set; import com.google.common.base.Objects; import com.google.common.collect.Constraint; import com.google.common.collect.Constraints; import com.google.common.collect.Sets; public class TryConstraint { // create a class A public static class A { private int a; public A(int a) { this.a = a; } public int getA() { return this.a; } @Override public String toString() { return String.format("[a=%d]", this.a); } @Override public boolean equals(Object obj) { if (obj != null || !(obj instanceof A)) { return false; } else { A aA = (A)obj; return aA.a == this.a; } } @Override public int hashCode() { return Objects.hashCode(this.a); } } public static void main(String[] args) { // Create a specified constraint Constraint<A> aConstraint = new Constraint<TryConstraint.A>() { @Override public A checkElement(A aA) { if (aA == null) { throw new NullPointerException(); } if (aA.getA() % 2 == 0) { throw new RuntimeException("Can't be even"); } return aA; } }; HashSet<A> aSet = Sets.newHashSet(new A(0), new A(1), new A(2), new A(3)); // Returns a constrained view of the specified set, using the specified constraint. // Any operations that add new elements to the set will call the provided constraint. // However, this method does not verify that existing elements satisfy the constraint. Set<A> newSet = Constraints.constrainedSet(aSet, aConstraint); System.out.println(newSet); // [[a=3], [a=1], [a=2], [a=0]] newSet.add(new A(5)); newSet.add(new A(5)); System.out.println(newSet); // [[a=3], [a=1], [a=2], [a=5], [a=5], [a=0]] newSet.add(null); System.out.println(newSet); // will throw NullPointerException newSet.add(new A(6)); System.out.println(newSet); // will throw RuntimeException } }