问题
Can anybody please tell me what are those possible purposes of allocating zero-length buffer?
ByteBuffer.allocate(0); // no IllegalArgumentException
Why the one who designed the API did this?
Thanks for comments and answers.
I hope there will be an update like this. :)
public abstract class ByteBuffer
extends Buffer
implements Comparable<ByteBuffer> {
public static final ByteBuffer VOID = allocate(0);
}
回答1:
If you have a method that must return a ByteBuffer
and returning null
is inappropriate for whatever reason, but you have no data to return, then returning a zero-length ByteBuffer
would satisfy those conditions.
回答2:
This can be used to implement Null Object design pattern http://en.wikipedia.org/wiki/Null_Object_pattern, similar to Collections.emptyList and others, creates an immutable object that can be reused.
来源:https://stackoverflow.com/questions/18223481/allocating-zero-capacity-bytebuffer