Java NIO 提供七種基本緩衝區類別(ByteBuffer、ShortBuffer、IntBuffer、CharBuffer、FloatBuffer、DoubleBuffer、LongBuffer),均無公共建構子,需透過靜態工廠方法建立。本文詳細比較 allocate、wrap、allocateDirect 三種建立方式的差異與適用場景。
IntBuffer.get() 回傳 int)。allocate(int capacity) 與 wrap(array) 靜態方法。capacity() 回傳緩衝區容量(元素個數,非位元組數)。array() 可轉回陣列,但唯讀緩衝區與直接緩衝區不支援,需先用 hasArray() 判斷。capacity。capacity 可設極大(如 1M)。IntBuffer.allocate(1024) 可容納 1024 個 int(4096 位元組),非 1024 位元組。offset、length)零複製封裝為緩衝區。capacity() 仍為原陣列長度,非子陣列長度。int[] arr = {1,2,3,4,5,6};
IntBuffer buf = IntBuffer.wrap(arr, 1, 3); // 封裝索引 1~3
for (int v : buf.array()) System.out.print(v + " "); // 輸出 1 2 3 4 5 6(原陣列全輸出)
array()。isDirect() 判斷是否為直接緩衝區。CharBuffer.wrap(CharSequence) 可接受 String、StringBuffer、StringBuilder、CharBuffer 本身,支援子字串範圍 wrap(csq, start, end)。
CharBuffer cb1 = CharBuffer.wrap("Hello");
CharBuffer cb2 = CharBuffer.wrap(new StringBuffer("World"));
CharBuffer cb3 = CharBuffer.wrap("1234", 1, 3); // "23"
根據效能需求與資料來源選擇建立方式:一般情況用 allocate;已有陣列/字串用 wrap 零複製;極高效能 I/O 且確認平台相容才用 allocateDirect。理解 hasArray()、isDirect() 等檢查方法,避免執行期例外。