Google Guava学习之Constraint
2011-06-08 16:35
351 查看
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 } }
相关文章推荐
- Guava学习笔记:Google Guava 类库简介
- Google Guava14.0 瓜娃学习笔记
- Google Guava学习(1) --- Guava入门
- [Google Guava]学习--新集合类型Multimap
- Google-Guava学习:新集合类型
- Google Guava学习计划第一章Guava Utilities—Preconditions_ComparisonChain_Strings_CharMatcher
- Guava学习笔记:Google Guava 类库简介
- Google Guava学习(10)-Guava字符串工具CharMatcher
- Google Guava学习计划第一章Guava Utilities—StopWatch和ServerLoader
- Guava学习笔记:Google Guava 类库简介
- Google Guava学习(5)-Guava Throwables类
- Google Guava学习(9)-Guava Cache缓存工具(二)
- java开发人员,最应该学习和熟练使用的工具类。google guava.(谷歌 瓜娃)
- Google Guava学习之BiMap
- Guava学习笔记一:Google Guava 类库简介
- [Google Guava]学习--新集合类型Multimap
- Google Guava学习(6)-Guava集合工具 Multiset
- Guava学习笔记:Google Guava 类库简介
- [Google Guava]学习--缓存cache
- Guava学习笔记(二):Google Guava (瓜娃)的API快速熟悉使用