标签:must selector system state shc exception element inter zha
前置条件:让方法调用的前置条件判断更简单。
Guava在Preconditions类中提供了若干前置条件判断的实用方法,我们建议[在Eclipse中静态导入这些方法]每个方法都有三个变种:
boolean flag=false;
checkArgument(flag);
运行结果:
Exception in thread "main" java.lang.IllegalArgumentException
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:108)
at guavaDemo.Test02.main(Test02.java:9)
当然此方法有很多重载方法,这里我们介绍一个演示一下:
int max=1,min=2;//我们期待max是大于min的
checkArgument(max>min,"max的值小于min的值");
运行结果:
Exception in thread "main" java.lang.IllegalArgumentException: max的值小于min的值
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:122)
at guavaDemo.Test02.main(Test02.java:12)
String str=null;
checkNotNull(str);
运行结果:
Exception in thread "main" java.lang.NullPointerException
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:770)
at guavaDemo.Test02.main(Test02.java:15)
String str=null;
checkState(str.isEmpty());
运行结果:
Exception in thread "main" java.lang.NullPointerException
at guavaDemo.Test02.main(Test02.java:17)
int[] arr=new int[5];
checkElementIndex(5, arr.length);
运行结果:
Exception in thread "main" java.lang.IndexOutOfBoundsException: index (5) must be less than size (5)
at com.google.common.base.Preconditions.checkElementIndex(Preconditions.java:1177)
at com.google.common.base.Preconditions.checkElementIndex(Preconditions.java:1159)
at guavaDemo.Test02.main(Test02.java:20)
checkPositionIndex(5, arr.length);
5位置存在,运行正常。checkPositionIndex(6, arr.length);
6位置不存在,抛出异常。Exception in thread "main" java.lang.IndexOutOfBoundsException: index (6) must not be greater than size (5)
at com.google.common.base.Preconditions.checkPositionIndex(Preconditions.java:1222)
at com.google.common.base.Preconditions.checkPositionIndex(Preconditions.java:1204)
at guavaDemo.Test02.main(Test02.java:22)
checkPositionIndexes(3, 6, arr.length);
Exception in thread "main" java.lang.IndexOutOfBoundsException: index (6) must not be greater than size (5)
at com.google.common.base.Preconditions.checkPositionIndex(Preconditions.java:1222)
at com.google.common.base.Preconditions.checkPositionIndex(Preconditions.java:1204)
at guavaDemo.Test02.main(Test02.java:22)
上面就是guava中为我们提供的一些最基本的前置条件检查方法。
接下来我们看看guava给我提供的equals方法和hashcode方法,代码比较简单这里就不详细说明了。
System.out.println(Objects.equal(null, ‘a‘));
System.out.println(Objects.equal(null, null));
System.out.println(Objects.equal(‘a‘, null));
System.out.println(Objects.equal(‘a‘,‘a‘));
String str1="zhaotong1";
System.out.println(Objects.hashCode(str1));
执行结果:
false
true
false
true
-1420540160
标签:must selector system state shc exception element inter zha
原文地址:https://www.cnblogs.com/sandea/p/8920383.html