java实现缓冲区(附完整源码)
时间: 2023-10-17 15:09:32 浏览: 41
以下是一个简单的Java缓冲区实现,包括完整的源代码:
```
public class MyBuffer {
private char[] buffer;
private int capacity;
private int position;
private int limit;
private int mark = -1;
public MyBuffer(int capacity) {
this.capacity = capacity;
buffer = new char[capacity];
limit = capacity;
}
public int capacity() {
return capacity;
}
public int position() {
return position;
}
public void position(int newPosition) {
if (newPosition > limit || newPosition < 0) {
throw new IllegalArgumentException();
}
position = newPosition;
if (mark > position) {
mark = -1;
}
}
public int limit() {
return limit;
}
public void limit(int newLimit) {
if (newLimit > capacity || newLimit < 0) {
throw new IllegalArgumentException();
}
limit = newLimit;
if (position > limit) {
position = limit;
}
if (mark > limit) {
mark = -1;
}
}
public void mark() {
mark = position;
}
public void reset() {
if (mark == -1) {
throw new InvalidMarkException();
}
position = mark;
}
public boolean isReadOnly() {
return false;
}
public boolean hasRemaining() {
return position < limit;
}
public int remaining() {
return limit - position;
}
public char get() {
if (position == limit) {
throw new BufferUnderflowException();
}
return buffer[position++];
}
public MyBuffer put(char c) {
if (position == limit) {
throw new BufferOverflowException();
}
buffer[position++] = c;
return this;
}
public MyBuffer flip() {
limit = position;
position = 0;
mark = -1;
return this;
}
public MyBuffer rewind() {
position = 0;
mark = -1;
return this;
}
public MyBuffer clear() {
position = 0;
limit = capacity;
mark = -1;
return this;
}
}
```
该缓冲区实现具有基本的get和put操作,以及flip,rewind和clear方法。它还具有标记的功能,可以在指定位置设置标记,并在需要时将缓冲区重置为该标记。此外,它还包括一些异常处理,例如BufferUnderflowException和BufferOverflowException。
请注意,此实现是基于字符数组的,因此只适用于char类型数据。如果需要支持其他数据类型,请相应地更改实现。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)