Cow Pow Pow
Cow Pow Pow

Reputation: 127

What is the purpose of a Buffer in Java?

Buffer is an abstract class having concrete subclasses such as ByteBuffer, IntBuffer, etc. It seems to be a container of data of a specific primitive type. What are the benefits of a Buffer? Why wouldn't I just use an array or a list?

Upvotes: 2

Views: 15401

Answers (1)

paxdiablo
paxdiablo

Reputation: 882596

A buffer can be defined, in its simplest form, as a contiguous block of memory of some type. Hence a byte buffer of size 4K (4096 bytes) may occupy memory locations 0xf000 through 0xffff inclusive.

As to why a buffer type may be used instead of an array or list, neither of those two alternatives have the in-built features of limit, position or mark.

On the first item, a buffer separates the capacity from the limit in that you can have a capacity of 1000 with a current limit of 10. In other words, it enforces the ability to have a variable size up to and including the capacity.

For the other two features, the current position provides an in-built way to read or write the next element, easing sequential processing, and the mark provides a way to save the current position for later reset.

All these features would require extra variables if you needed them in conjunction with an array or list.

Of course, if you don't need any of these features then, by all means, use an array.

Upvotes: 10

Related Questions