Convenience Method, Anyone?

Hi, There:

It’s been a while again. I am posting a quick one on Java Convenience Method, like this:

public static Integer addAll(Integer... nums) {
     Integer sum = 0;
     for (Integer num:nums) sum += num; 
     return sum; 
}

In comparison with a typical Array version:

public static Integer addAll(Integer[] nums) {
     Integer sum = 0;
     for (Integer num:nums) sum += num; 
     return sum; 
}

They both work fine with variable number of Integers and Integer[], respectively. But the problem is that if you put both of them in the same Class, the compile will complain about the “Duplicate Method” error. So it is apparent that the compiler treats the two method signature the same way and considers them to be identical.

It is said the Convenience Method is really a cosmetic syntax. In order to compare them, I looked at them using a Bytecode examiner. The two methods, respectively, showed up like this:

public static java.lang.Integer addAll(java.lang.Integer... nums);
 0 iconst_0
 1 invokestatic java.lang.Integer.valueOf(int) : java.lang.Integer [28]
...

and

 public static java.lang.Integer addAll(java.lang.Integer[] nums);
 0 iconst_0
 1 invokestatic java.lang.Integer.valueOf(int) : java.lang.Integer [28]
...

This means the ByteCode Inspector doesn’t tell us the real differences at all. Then I decided to examine it in runtime, using Reflection to reveal the Method Type . The result showed that both methods have identical signature like this:

public static java.lang.Integer ConvenienceTest.addAll(java.lang.Integer[])

This proves that both method are still different in Bytecode, but possess identical signature as Integer[] when translated into machine code in the JVM.

So why would you want to use the variable arguments over the Array version? I guess the keyword is “Convenience“, in that when this method is called, one can conveniently stack the Integer up into the arguments.  But personally, I think if I have more than three arguments, I would prefer to use the Array version. What do you think?

Best,

-Tony

 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

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