Blog Archives

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) {
 put(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];
 put(key,value);
 }
 }
 
 
 
}

 

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) {
 System.out.println(y.get("Name"));
 System.out.println(y.get("Age"));
 System.out.println(y.get("Address"));
 System.out.println(y.get("22"));
 
 }

Which produces the result:-

John
34
test
null

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.

My Netbeans.org… very very nice

Ok, I did try facebook, I really did but I was just bombarded with so much stuff (and I know you can “turn it off”) that i decided to quit that.

http://my.netbeans.org/ is a social networking site for us Beanies. Its beautifully done actually, some really nice ajax. So I’ll see how I get on with that, being that I am quite an introvert, at present I don’t have any friends but I’m sure that will change soon.