Data Structures (structs)

Before I start explaining Data Structures, better known as structs, I am going to clarify something. Structs are not available in Java and while I will give an example of making the equivalent of one in the language, it is highly recommended that it is not used. The reason for this will be explained when I show the example for that language. With that in mind, C# and C++ users will benefit from the explanation of this.

In its most basic form, a struct is merely a group of data elements that have been combined together in one name. Many people will think that this is similar to a class, but there is a notable difference. Classes are intended to be private by default whereas structs are intended to be public by default. With this in mind, I will show how a struct is declared in C/C++ then go more into detail.

struct item {
string name;
int stock;
};

This is the item struct, inside of this is the name of the item and how much of its stock we have. As mentioned before, both of the variables inside of this group are publicly accessible. Let's say we make a variable based on this struct and want to access the name and stock afterwards.

item hitchhikers;
hitchhikers.name = "Hitchhiker's Guide To The Galaxy";
hitchhikers.stock = 42;
cout << hitchhikers.name << " has " << hitchhikers.stock << " in stock.";

The C++ example I gave shows me setting hitchhikers.name and hitchhikers.stock, then accessing them to print out what is in stock. Now many will ask what is the benefit to using structs when compared to classes. The basic reality is that when performance and a smaller memory footprint are needed, structs are superior so long as the features used in Object Oriented Programming are not required.

Now, struct based behavior can be replicated in Java by making a finalized class. Here's an example of item as a finalized class.

final class Item {
string name;
int stock;
}

Allow me to mention upfront that the performance gain seen from structs will not apply in Java, thus making this an unnecessary task. In addition, Java was made to be more Object Oriented so using a finalized class as a struct type effectively undermines this. What I have shown is the most basic usage of using a struct as there are several ways that this can be utilized in C++ and C# given how each language is designed.

Special thanks to jip for helping peer review this.