地区分类 数组 Java NIO 缓冲区基础二

电脑杂谈  发布时间:2017-02-15 00:05:01  来源:网络整理

现在让我们在看看缓冲区的一些细节。

1、缓冲区的创建

之前也许你已经看到了。我们使用alocate方法创建一个缓冲区。下面是一个创建方法集合。

public abstract class CharBuffer
extends Buffer implements CharSequence, Comparable {
// This is a partial API listing 
public static CharBuffer allocate(int capacity);
public static CharBuffer wrap (char [] array);
public static CharBuffer wrap (char [] array, int offset, int length);
public final boolean hasArray( ) 
public final char [] array( )
public final int arrayOffset( ) 
}

注意,这些都是静态方法。

wrap方法使用一个现有的数组作为缓冲区备份。这里很重要,因为,其实缓冲区都需要这样一个真正存放数据的地方,我们可以看看如果allocate方法

/**
     * Allocates a new byte buffer.
     *
     * <p> The new buffer's position will be zero, its limit will be its
     * capacity, and its mark will be undefined.  It will have a {@link #array
     * </code>backing array<code>}, and its {@link #arrayOffset </code>array
     * offset<code>} will be zero.
     *
     * @param  capacity
     *         The new buffer's capacity, in bytes
     *
     * @return  The new byte buffer
     *
     * @throws  IllegalArgumentException
     *          If the <tt>capacity</tt> is a negative integer
     */
 public static ByteBuffer allocate(int capacity) {
	if (capacity < 0)
	    throw new IllegalArgumentException();
	return new HeapByteBuffer(capacity, capacity);
    }

HeapByteBuffer又是什么呢?继续跟踪

HeapByteBuffer(int cap, int lim) {		// package-private

	super(-1, 0, lim, cap, new byte[cap], 0);
	/*
	hb = new byte[cap];
	offset = 0;
	*/

    }


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-32465-1.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    • 乔舜
      乔舜

      当心被控告到时候会赔死

    • 孙黎明
      孙黎明

      应该趁势说明由于国家利益受到美国侵害使相关岛屿军事化

    • 裴房露
      裴房露

      加油

    热点图片
    拼命载入中...