I want store a list of doubles and ints to a ByteBuffer, which asks for a size to allocate. I'd like to write something like C's syntax
int size=numDouble*sizeof(double)+numInt*sizeof(int);
But there is no sizeof
in Java. What is the best practice to calculate the size in byte? Should I hardcode it?
The size of a data type is given by (name of datatype). SIZE. The maximum value that it can store is given by (Name of data type). MAX_VALUE.
The size or range of the data that can be stored in an integer data type is determined by how many bytes are allocated for storage. Because a bit can hold 2 values, 0 or 1, you can calculate the number of possible values by calculating 2n where n is the number of bits.
Overview. sizeOf() is a static method of the FileUtils class that is used to get the size of the specified file or directory in bytes. If the file provided is a regular file, then the file's length is returned. If the argument is a directory, then the size of the directory is calculated recursively.
Similarly, there is is no sizeof() operator in Java. All primitive values have predefined size, e.g., int is 4 bytes, char is 2 byte, short is 2 byte, long and float is 8 byte, and so on.
See @Frank Kusters' answer, below!
(My original answer here was for Java versions < 8.)
Since Java 8, all wrapper classes of primitive types (except Boolean
) have a BYTES
field. So in your case:
int size = numDouble * Double.BYTES + numInt * Integer.BYTES;
Documentation: http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With