ByteBuffer data structure

ByteBuffer is the niO part of Java. It is often used in high end programming operations. If you use network programming, such as Android hard codec (MediaCodeC)…

Part of the

  • Byte [] bytes: stores data
  • Int capacity: Specifies the capacity of bytes. Capacity is equal to bytes.size(), which is immutable after bytes are initialized.
  • Int limit: Indicates how much data is actually stored in bytes. It can be easily imagined that limit <= capacity is flexible
  • Int position: Indicates the position at which data is to be written or read to bytes. This value is flexible

How to create

ByteBuffer. Allocate (int cap) Creates a ByteBuffer that specifies the size of the container.

How to understand

Position is a very important place, and the source of data starts from position. The position variable tracks how much data has been written. More precisely, it specifies which element of the array the next byte will be placed in. For example, position moves backwards after put/ GET.

Position can also be manually controlled:

byteBuffer.position(0); // Set position to 0 so that data is read from this positionCopy the code

Sample code:

public class Test5 { public static void main(String[] args) { ByteBuffer byteBuffer = ByteBuffer.allocate(20); System.out.println(" Create a byteBuffer of size 20 "); System.out.println(" output raw byteBuffer"); System.out.println(byteBuffer); System.out.println(Arrays.toString(byteBuffer.array())); byte[] bytes = new byte[10]; for (int i = 0; i< bytes.length; i++){ bytes[i] = (byte) i; } byteBuffer.put(bytes); System.out.println(" Output byteBuffer after put(bytes) "); System.out.println(byteBuffer); System.out.println(Arrays.toString(byteBuffer.array())); byte[] byte2 = new byte[10]; byteBuffer.get(byte2); System.out.println(" byteBuffer after get(byte2) "); System.out.println(byteBuffer); System.out.println(Arrays.toString(byteBuffer.array())); System.out.println(Arrays.toString(byte2)); System. The out. Println (" mobile position "); byteBuffer.position(0); byteBuffer.get(byte2); System.out.println(" Print byteBuffer after get(byte2) again "); System.out.println(byteBuffer); System.out.println(Arrays.toString(byteBuffer.array())); System.out.println(Arrays.toString(byte2)); }}Copy the code

Running results:

Create a byteBuffer output capacity of 20 original byteBuffer Java nio. HeapByteBuffer [pos = 0 lim = 20 cap = 20] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] Output byteBuffer java.nio.heapByteBuffer [pos=10 lim=20 cap=20] [0, 1, 2, 3, 4, 5, 6, 7 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] byteBuffer java.nio.heapByteBuffer [pos=20 lim=20 cap=20] 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0, 0, Java.nio.heapbytebuffer [pos=10 lim=20 cap=20] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]Copy the code