Java ByteBuffer Clear clearAndEnsureCapacity(ByteBuffer buffer, int elements)

Here you can find the source of clearAndEnsureCapacity(ByteBuffer buffer, int elements)

Description

Ensure the buffer's capacity is large enough to hold a given number of elements.

License

Open Source License

Parameter

Parameter Description
elements The required number of elements to be appended to the buffer.
buffer The buffer to check or <code>null</code> if a new buffer should be allocated.

Return

Returns the same buffer or a new buffer with the given capacity.

Declaration

public static ByteBuffer clearAndEnsureCapacity(ByteBuffer buffer, int elements) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.nio.ByteBuffer;
import java.nio.CharBuffer;

public class Main {
    /**//from   w ww .jav a 2 s  .c o  m
     * Ensure the buffer's capacity is large enough to hold a given number
     * of elements. If the input buffer is not large enough, a new buffer is allocated
     * and returned.
     * 
     * @param elements The required number of elements to be appended to the buffer.
     * 
     * @param buffer
     *          The buffer to check or <code>null</code> if a new buffer should be
     *          allocated.
     *
     * @return Returns the same buffer or a new buffer with the given capacity. 
     */
    public static ByteBuffer clearAndEnsureCapacity(ByteBuffer buffer, int elements) {
        if (buffer == null || buffer.capacity() < elements) {
            buffer = ByteBuffer.allocate(elements);
        } else {
            buffer.clear();
        }
        return buffer;
    }

    /**
     * Ensure the buffer's capacity is large enough to hold a given number
     * of elements. If the input buffer is not large enough, a new buffer is allocated
     * and returned.
     * 
     * @param elements The required number of elements to be appended to the buffer.
     * 
     * @param buffer
     *          The buffer to check or <code>null</code> if a new buffer should be
     *          allocated.
     *
     * @return Returns the same buffer or a new buffer with the given capacity. 
     */
    public static CharBuffer clearAndEnsureCapacity(CharBuffer buffer, int elements) {
        if (buffer == null || buffer.capacity() < elements) {
            buffer = CharBuffer.allocate(elements);
        } else {
            buffer.clear();
        }
        return buffer;
    }
}

Related

  1. clear(ByteBuffer b)
  2. clear(ByteBuffer buffer)
  3. clear(ByteBuffer buffer, int position, int length, byte filler)
  4. clear(ByteBuffer[] buffers)
  5. clearAll(ByteBuffer[] buffers)
  6. clearRemaining(ByteBuffer buffer)
  7. clearRemainingFrame(ByteBuffer buffer, int position)
  8. clearString(ByteBuffer buffer)
  9. fillBuffer(ReadableByteChannel channel, ByteBuffer buf, boolean clear)