Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object arrays in method signatures

Consider the following method signatures:

public fooMethod (Foo[] foos) { /*...*/ }

and

public fooMethod (Foo... foos) { /*...*/ }

Explanation: The former takes an array of Foo-objects as an argument - fooMethod(new Foo[]{..}) - while the latter takes an arbitrary amount of arguments of type Foo, and presents them as an array of Foo:s within the method - fooMethod(fooObject1, fooObject2, etc...).

Java throws a fit if both are defined, claiming that they are duplicate methods. I did some detective work, and found out that the first declaration really requires an explicit array of Foo objects, and that's the only way to call that method. The second way actually accepts both an arbitrary amount of Foo arguments AND also accepts an array of Foo objects.

So, the question is, since the latter method seems more flexible, are there any reasons to use the first example, or have I missed anything vital?

like image 561
Henrik Paul Avatar asked Oct 06 '08 12:10

Henrik Paul


People also ask

What is method signature in OOP?

The method signature in java is defined as the structure of the method that is designed by the programmer. The method signature is the combination of the method name and the parameter list. The method signature depicts the behavior of the method i.e types of values of the method, return type of the method, etc.

How do you pass an array of objects to a method in Java?

Passing Array To The Method In Java To pass an array as an argument to a method, you just have to pass the name of the array without square brackets. The method prototype should match to accept the argument of the array type. Given below is the method prototype: void method_name (int [] array);

What is a method signature example in Java?

Example. Live Demo public class MethodSignature { public int add(int a, int b){ int c = a+b; return c; } public static void main(String args[]){ MethodSignature obj = new MethodSignature(); int result = obj. add(56, 34); System. println(result); } }

Why is it necessary for method signature in a class?

In Java, a method signature is part of the method declaration. It's the combination of the method name and the parameter list. The reason for the emphasis on just the method name and parameter list is because of overloading. It's the ability to write methods that have the same name but accept different parameters.


1 Answers

These methods are actually the same.

This feature is called varargs and it is a compiler feature. Behind the scenes is is translates to the former version.

There is a pitfall if you define a method that accepts Object... and you sent one parameter of type Object[]!

like image 85
Shimi Bandiel Avatar answered Oct 14 '22 03:10

Shimi Bandiel