1. 程式人生 > >IntBuffer類的基本用法

IntBuffer類的基本用法

容量 city out ava test buffer eat ati nis

package com.ietree.basicskill.socket.basic.nio;

import java.nio.IntBuffer;

/**
 * Created by Administrator on 2017/5/25.
 */
public class BufferTest {
    public static void main(String[] args) {
         // 1 基本操作
         /*//創建指定長度的緩沖區
         IntBuffer buf = IntBuffer.allocate(10);
         buf.put(13);// position位置:0 - > 1
         buf.put(21);// position位置:1 - > 2
         buf.put(35);// position位置:2 - > 3
         //把位置復位為0,也就是position位置:3 - > 0
         buf.flip();
         System.out.println("使用flip復位:" + buf);
         System.out.println("容量為: " + buf.capacity());    //容量一旦初始化後不允許改變(warp方法包裹數組除外)
         System.out.println("限制為: " + buf.limit());        //由於只裝載了三個元素,所以可讀取或者操作的元素為3 則limit=3

         System.out.println("獲取下標為1的元素:" + buf.get(1));
         System.out.println("get(index)方法,position位置不改變:" + buf);
         buf.put(1, 4);
         System.out.println("put(index, change)方法,position位置不變:" + buf);;

         for (int i = 0; i < buf.limit(); i++) {
             //調用get方法會使其緩沖區位置(position)向後遞增一位
             System.out.print(buf.get() + "\t");
         }
         System.out.println("buf對象遍歷之後為: " + buf);
*/ // 2 wrap方法使用 // wrap方法會包裹一個數組: 一般這種用法不會先初始化緩存對象的長度,因為沒有意義,最後還會被wrap所包裹的數組覆蓋掉。 // 並且wrap方法修改緩沖區對象的時候,數組本身也會跟著發生變化。 /*int[] arr = new int[]{1,2,5}; IntBuffer buf1 = IntBuffer.wrap(arr); System.out.println(buf1); IntBuffer buf2 = IntBuffer.wrap(arr, 0 , 2); //這樣使用表示容量為數組arr的長度,但是可操作的元素只有實際進入緩存區的元素長度 System.out.println(buf2);
*/ // 3 其他方法 IntBuffer buf1 = IntBuffer.allocate(10); int[] arr = new int[]{1,2,5}; buf1.put(arr); System.out.println(buf1); //一種復制方法 IntBuffer buf3 = buf1.duplicate(); System.out.println(buf3); //設置buf1的位置屬性 //buf1.position(0);
buf1.flip(); System.out.println(buf1); System.out.println("可讀數據為:" + buf1.remaining()); int[] arr2 = new int[buf1.remaining()]; //將緩沖區數據放入arr2數組中去 buf1.get(arr2); for(int i : arr2){ System.out.print(Integer.toString(i) + ","); } } }

IntBuffer類的基本用法