Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Why is it not Allowed in Java to Overload Foo(Object…) with Foo(Object[])?

DZone's Guide to

Why is it not Allowed in Java to Overload Foo(Object…) with Foo(Object[])?

· Java Zone ·
Free Resource

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

 This is from Why is it not allowed in Java to overload Foo(Object…) with Foo(Object[])?

Question

I was wondering why it is not allowed in Java to overload Foo(Object[] args) with Foo(Object... args), though they are used in a different way?

Foo(Object[] args){}

is used like:
 
Foo(newObject[]{newObject(),newObject()});

while the other form:
 
Foo(Object... args){}

is used like:
 
Foo(newObject(),newObject());

Is there any reason behind this?

Answer

This 15.12.2.5 Choosing the Most Specific Method talk about this, but its quite complex. e.g. Choosing between Foo(Number... ints) and Foo(Integer... ints)
In the interests of backward compatibility, these are effectively the same thing.

publicFoo(Object... args){}// syntactic sugar for Foo(Object[] args){}// calls the varargs method.Foo(newObject[]{newObject(),newObject()});

e.g. you can define main() as
 
publicstaticvoid main(String... args){
 


A way to make them different is to take one argument before the varargs

publicFoo(Object o,Object... os){}publicFoo(Object[] os){}Foo(newObject(),newObject());// calls the first.Foo(newObject[]{newObject(),newObject()});// calls the second.
 


They are not exactly the same. The subtle difference is that while you can pass an array to a varargs, you can't treat an array parameter as a varargs.

publicFoo(Object... os){}publicBar(Object[] os){}Foo(newObject[]{newObject(),newObject()});// compiles fine.Bar(newObject(),newObject());// Fails to compile.

Additionally, a varags must be the last parameter.

publicFoo(Object... os,int i){}// fails to compile.publicBar(Object[] os,int i){}// compiles ok.

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}