---
title: "guava笔记9-Ranges"
author: "leadtoit"
date: "2013-10-22T13:38:53Z"
tags: []
categories: ["编程语言"]
slug: "guava-9-ranges"
draft: false
lastmod: "2013-10-21T18:03:14Z"
id: 1961747
url: "https://leadtoit.iteye.com/blog/1961747"
---

很多时候，我们需要表示一个数据范围，可能会这样传参数：

inScope(int min, int max, boolean minInclude, boolean maxInclude)

这样的代码看起来很繁琐。

Guava提供了一种数据结构叫做Range，正好用于表达这样一种数据。

 

Range提供了一些静态工厂方法，用于构造各种是否包含边界的范围：

**Notation**

**Definition**

**Factory method**

(a..b)

{x | a &lt; x &lt; b}

[open](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Range.html#open%28C,%20C%29)

\[a..b]

{x | a &lt;= x &lt;= b}

[closed](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Range.html#closed%28C,%20C%29)

(a..b]

{x | a &lt; x &lt;= b}

[openClosed](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Range.html#openClosed%28C,%20C%29)

[a..b)

{x | a &lt;= x &lt; b}

[closedOpen](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Range.html#closedOpen%28C,%20C%29)

(a..+∞)

{x | x &gt; a}

[greaterThan](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Range.html#greaterThan%28C%29)

[a..+∞)

{x | x &gt;= a}

[atLeast](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Range.html#atLeast%28C%29)

(-∞..b)

{x | x &lt; b}

[lessThan](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Range.html#lessThan%28C%29)

(-∞..b]

{x | x &lt;= b}

[atMost](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Range.html#atMost%28C%29)

(-∞..+∞[]()[]())

{x}

[all](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Range.html#all%28%29)

   
如：Range.openClosed(4,6) 就表示(4,6]这样的范围，其实包含数据5,6。

range的参数支持范型，这样任何实现Comparable的对象都能用于Range。

此外，Range也能通过参数指定是否包含边界：  
range(C, BoundType, C, BoundType) : 如range(4, BoundType.CLOSE,6, BoundType.OPEN) 表示[4,6)  
downTo(C, BoundType) 表示(a..+∞) or [a..+∞)  
upTo(C, BoundType) 表示(-∞..b) or (-∞..b]

得到Range对象后，Range提供了一些方法来使用Range对象：  
contains(c)：判断是否包含数据c  
containsAll(list)：判断是否包含集合所有数据  
hasLowerBound() and hasUpperBound(): 判断是否包含下边界及上边界  
lowerBoundType() and upperBoundType() ：返回边界包含类型（OPEN or CLOSED），如果没有边界将抛IllegalStateException  
lowerEndpoint() and upperEndpoint() :返回边界值，如果没有边界将抛IllegalStateException  
isEmpty() ：是否是空范围，如(4,4]

集合处理：  
Encloses：是否包含，如：\[3..6] encloses \[4..5]，\[4..5] does not enclose (3..6)  
isConnected：两个范围是否是相邻的，如：\[3,5]与(5,10)相邻，(0,9)与(5,10)相邻，(3,5)与（5,10）不相邻  
Intersection：返回2个范围的交集。如果两个范围不相邻，抛IllegalArgumentException。  
如：(3,5]与\[5,10]的交集是\[5,5];(0,9)和(3,4)的交集是(3,4)  
Span: 返回包含2个范围的最小范围，如：(1, 5)和(6, 10)的span是(1,10)