Is it possible to replicate a Union in Java?

Asked

Viewed 89 times

4

As unionthe ones I’m talking about are the same as C/C++. The goal of union is to save memory using the same region of it to store different data at different times.

It’s like a hotel room. Different people live in it for periods of time that don’t overlap. These people never meet and usually know nothing about each other. By properly managing the shared time of the rooms (i.e., ensuring that different people are not assigned to a room at the same time), a reasonably small hotel can offer accommodation for a relatively large number of people.

Is it possible to replicate this behavior in Java? If so, how?

I have no idea how it would be possible to do something like this in Java, nor do I know if it even allows memory management, so thank you for any help.

  • This may help, but I’m not sure how effective it is: https://www.guj.com.br/t/resolvido-union-ou-similhante-em-java/81499/13

1 answer

4


General behavior is possible through a library that has a structure that simulates this, but replicates the specific behavior of a union of C is not gives, the language has no mechanism for this (unlike C#).

union is very efficient and is mainly used to communicate with hardware. Java does not do this communication directly and the whole is so inefficient in other things that it would be ridiculous to have a mechanism that does this kind of economy to the extreme (C# already likes to communicate with low-level things and have fewer layers interfering, yet has limitations).

A library gives this capability but you will have a huge object, allocating in heap, In many cases it doesn’t even make up for the use. This may change with the new type by value that Java will have in the next versions, but it will not yet have the same level of efficiency. Example.

There’s even some way to do it with unsafe code, but it’s very complex, and actually anything you can do with unsafe code, it’s outside the scope of Java itself. And it doesn’t mean that it has the same efficiency, only that it approaches in some points.

  • 1

    If I use native methods, the communication between union C/C++ and the rest of the code in Java? Or would it be feasible?

  • 1

    Viable is, but it doesn’t pay off in the vast majority of cases, Java chose to make it very difficult to do this. When they created they had a vision of pure language.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.