Reputation: 65
I have a requirement where I have to create my own data type and i should assign some bytes to the data types.
Example:
Datatype A : should have 1 byte of memory
Datatype B : should have 2 bytes of memory
Datatype C : should have 7 bytes of memeory etc..
Is there any way we can define our own data types and allocate some memory to them ?
Upvotes: 0
Views: 7597
Reputation: 140457
There are a few "options" in Java to express types, namely: interfaces, classes, and enums.
In that sense, the best match would be a class, like:
public class TwoByteHolder {
public final byte[] data = new byte[2];
}
An object of that class allows you to exactly store 2 bytes; the next "level" could be something like:
public class ByteHolder {
public final byte[] data;
public ByteHolder(int numberOfBytes) {
data = new byte[ numberOfBytes ];
}
...
But of course: the memory overhead would be enormous - Java isn't the the best language to deal with such requirements.
Upvotes: 3
Reputation: 510
You can create a new class which has specific fields. If you need exact size of fields you can use byte arrays.
class Data {
public byte[] dataA = new byte[1];
public byte[] dataB = new byte[2];
public byte[] dataC = new byte[7];
...
}
Upvotes: 1
Reputation: 1074355
The only user-defined types available in Java are classes (including enums), and you cannot directly control how large they are. A class instance has many bytes of overhead you can't avoid having.
Upvotes: 1
Reputation: 985
You can't create data types in java, but you can create object classes, like this:
Class A {
public byte[] bytes;
}
Upvotes: 0