Guava教程
Range 表示一个间隔或一个序列。它被用于获取一组数字/串在一个特定范围之内。
以下是com.google.common.collect.Range<C>类的声明:
@GwtCompatible
public final class Range<C extends Comparable>
extends Object
implements Predicate<C>, Serializable
方法
方法继承
这个类从以下类继承的方法: java.lang.Object
选择使用任何编辑器创建以下java程序在 C:/> Guava
GuavaTester.java
import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomain;
import com.google.common.collect.Range;
import com.google.common.primitives.Ints;
public class GuavaTester {
public static void main(String args[]){
GuavaTester tester = new GuavaTester();
tester.testRange();
}
private void testRange(){
//create a range [a,b] = { x | a <= x <= b}
Range<Integer> range1 = Range.closed(0, 9);
System.out.print("[0,9] : ");
printRange(range1);
System.out.println("5 is present: " + range1.contains(5));
System.out.println("(1,2,3) is present: " + range1.containsAll(Ints.asList(1, 2, 3)));
System.out.println("Lower Bound: " + range1.lowerEndpoint());
System.out.println("Upper Bound: " + range1.upperEndpoint());
//create a range (a,b) = { x | a < x < b}
Range<Integer> range2 = Range.open(0, 9);
System.out.print("(0,9) : ");
printRange(range2);
//create a range (a,b] = { x | a < x <= b}
Range<Integer> range3 = Range.openClosed(0, 9);
System.out.print("(0,9] : ");
printRange(range3);
//create a range [a,b) = { x | a <= x < b}
Range<Integer> range4 = Range.closedOpen(0, 9);
System.out.print("[0,9) : ");
printRange(range4);
//create an open ended range (9, infinity
Range<Integer> range5 = Range.greaterThan(9);
System.out.println("(9,infinity) : ");
System.out.println("Lower Bound: " + range5.lowerEndpoint());
System.out.println("Upper Bound present: " + range5.hasUpperBound());
Range<Integer> range6 = Range.closed(3, 5);
printRange(range6);
//check a subrange [3,5] in [0,9]
System.out.println("[0,9] encloses [3,5]:" + range1.encloses(range6));
Range<Integer> range7 = Range.closed(9, 20);
printRange(range7);
//check ranges to be connected
System.out.println("[0,9] is connected [9,20]:" + range1.isConnected(range7));
Range<Integer> range8 = Range.closed(5, 15);
//intersection
printRange(range1.intersection(range8));
//span
printRange(range1.span(range8));
}
private void printRange(Range<Integer> range){
System.out.print("[ ");
for(int grade : ContiguousSet.create(range, DiscreteDomain.integers())) {
System.out.print(grade +" ");
}
System.out.println("]");
}
}
验证结果
使用javac编译器编译如下类
C:\Guava>javac GuavaTester.java
现在运行GuavaTester看到的结果
C:\Guava>java GuavaTester
看到结果
[0,9] : [ 0 1 2 3 4 5 6 7 8 9 ]
5 is present: true
(1,2,3) is present: true
Lower Bound: 0
Upper Bound: 9
(0,9) : [ 1 2 3 4 5 6 7 8 ]
(0,9] : [ 1 2 3 4 5 6 7 8 9 ]
[0,9) : [ 0 1 2 3 4 5 6 7 8 ]
(9,infinity) :
Lower Bound: 9
Upper Bound present: false
[ 3 4 5 ]
[0,9] encloses [3,5]:true
[ 9 10 11 12 13 14 15 16 17 18 19 20 ]
[0,9] is connected [9,20]:true
[ 5 6 7 8 9 ]
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ]
转载自并发编程网-ifeve.com