Declaring Objects Using Constructors in Java

So, I had a dillema last night where I was really getting irritated with my code and how messy it was when declaring objects and their elements.

Coincidentally it was at this same time I started getting fired up about how I definitely remember doing this in C# with no issues whatsoever, so this began my hunt to figure out how to declare objects and their elements in Java.

For starters, we will use a Complex HashMap.

When typing it in your IDE you need to declare it as the following:

HashMap<Integer, HashMap<String, String>> testHash = new HashMap<Integer, HashMap<String, String>>();

Next, what I want you to do is before the semicolon put the following:

{ { } }

With this you will be able to start adding elements as if you are declaring them in a typical JSON Format.

A fun tip for you to keep in mind is that you can actually use the IDE AutoComplete of CTRL+Enter or CTRL+Space to see what options you have available.

When you are done you will end up with an example that is sort of like this if you use the IDE Code Formatting to make it pretty:

JSON Style Adding to Java Objects - Enhanced

Here is an example I did with a more complex HashMap:

JSON Style Adding to Java Objects - Complex Example

An important thing to note here is that the same thing can be done with both the List/ArrayList and any Java Classes that you declare as long as you have a constructor.

I had a great time putting this together so let me know your thoughts, feedback, criticism below in the comments.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s