---
title: "边界检查函数checkBounds"
author: "xinyiwust"
date: "2012-08-27T14:12:36Z"
tags: []
categories: ["编程语言"]
slug: "checkbounds"
draft: false
lastmod: "2012-08-27T14:12:36Z"
id: 1663952
url: "https://xinyiwust.iteye.com/blog/1663952"
---

今天在看java.nio.Buffer的源码时，看到这样一个函数：

```java

    static void checkBounds(int off, int len, int size) { 
        if ((off | len | (off + len) | (size - (off + len))) < 0)
	    throw new IndexOutOfBoundsException();
    }

```

这是一个边界检查函数，感觉写的非常简洁，只要满足如下条件就抛出IndexOutOfBoundsException：
off<0或者len<0或者off+len超出了Integer的最大值或者size<(off+len)。
以后在检查数组越界的时候可以直接拿来用了。