David Thielen
David Thielen

Reputation: 32904

Is there a way to have the equivalent of a struct in Java 1.4?

Using the common example of a Point (x, y) object, is there a way to have it as a struct in Java 1.4? The advantage would be that there would not be a separate memory allocation for the Point object because the struct would be part of the containing object. But it would still have member functions to access it.

I'm 98% certain the answer is no but hope springs eternal...

what/why: In our code we have 100,000+ objects (about 12 - 14% of the total memory footprint) that is an int and a boolean. If that was a C# struct inside the object, it would reduce the number of objects. And... we are looking at making it just an int where 0x40000000 is the boolean value. But handling that is a lot easier if we have member methods for that int and it's treated as a struct.

Upvotes: 4

Views: 290

Answers (3)

user874577
user874577

Reputation:

An addition to tskuzzy's answer: another possibility would be to lift the int x and int y fields from the Point class into any classes that need to store point values.

Edit in response to comments:

One thing you could do is to have each class that needs to store a single point value extend a Point class. There would be no logical is-a relationship, but it gives you access to Point objects through a single interface. This wouldn't work (I don't think) for any classes that need to store multiple point values, though.

Upvotes: 1

ilcavero
ilcavero

Reputation: 3082

There is no struct equivalent on Java now, although I believe that they have been hinted for future versions. Still have a look at the flyweight pattern, might be what you are looking for http://en.wikipedia.org/wiki/Flyweight_pattern

Upvotes: 2

tskuzzy
tskuzzy

Reputation: 36446

No, you have to use Objects for general "structs".

However for simple data structures like pairs of ints, you can use a bit of trickery in order to save memory and increase speed.

int a = 9;
int b = 10;
long pair = (a << 32)|b;

This packs the 32 bits of a and b into a long. Here's how you extract them:

a = (int)(pair >> 32);
b = (int)pair;

Upvotes: 1

Related Questions