流殃的博客

| Comments

代码

package cn.shy.demo;

import javax.validation.constraints.Min;
import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
import java.util.*;
import java.util.concurrent.*;

public class test2 {
    public static void main(String[] args) {
        // Declaring the capacity of the ByteBuffer
        int capacity = 5;
        
        try {
            ByteBuffer bb1
                    = ByteBuffer.allocate(capacity);

            bb1.put((byte)10);
            bb1.put((byte)20);

            System.out.println("Original ByteBuffer: " + Arrays.toString(bb1.array()));
            System.out.println("\nposition:  "
                    + bb1.position());
            System.out.println("\ncapacity:  " + bb1.capacity());

            ByteBuffer bb2 = bb1.slice();

            System.out.println("\nshared subsequance ByteBuffer: " + Arrays.toString(bb2.array()));

            System.out.println("\nposition:  " + bb2.position());

            System.out.println("\ncapacity:  " + bb2.capacity());
        }

        catch (IllegalArgumentException e) {

            System.out.println("IllegalArgumentException catched");
        }

        catch (ReadOnlyBufferException e) {

            System.out.println("ReadOnlyBufferException catched");
        }
    }
}

截图结果

image.png

总结

下标从1开始
其实就是开辟了一个新的缓冲区,从源数据区中没有数据的地方开始
比如说ByteBuffer的容量是5,写入了两个数,此时位置是2,容量是5
slice之后,新的缓冲区起始位置是0,容量就是5-2=3

Comments

评论