Optional Parameters another way.

I’ve always liked the way that in C++ and other languages you can have optional parameters and I’ve been messing around with ways to do it in JAVA, so I came up with a class that extends the HashMap and makes it quite a neat way of having optional parameters in code.

Here’s the class

package utilclasses;
import java.util.HashMap;
 * Another fine Java Class http://www.netbeansboy.org
 * @author paulc
public final class optional extends HashMap {
 optional(Object... objects) {
 public void put(Object... objects) {
 for (int i=0;i<objects.length;i=i+2) {
 Object key=objects[i];
 Object value=objects[i+1];


As you can see it has one routine called put that is called in the constructor that constructs the hash map, so it’s use in your code is pretty simple.

 opt(new optional("Name","John","Age",34,"Address","test"));
 private static void opt(optional y) {

Which produces the result:-


Note that the last result is null because optional parameter 22 has not been set.  Note however this will only work with Java 8. I’ve actually used their optional solution to create mine! Only that I really like the idea of just filling out key values so you can see in your code the variables.


About Paul C

I am a Senior Java programmer/Web Technologies, Play in a band called Mandolin Monday, I have a cat and I live on a boat.

Posted on August 13, 2015, in Howto and tagged , . Bookmark the permalink. Leave a comment.

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

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

Twitter picture

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

Facebook photo

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


Connecting to %s

%d bloggers like this: