Learn Java Programming - Varargs Array Part 2 Tutorial

preview_player
Показать описание
This tutorial will discuss the rules for the proper usage of varargs. I will also show you some pitfalls that you should be aware of when integrating varargs into your programs.

The arguments passed to the method must be of a compatible data type to the varargs data type declaration.
When invoking a method, the argument may be passed as an array or as a sequence of arguments.
You may have other parameters in the method parameter list, but only one varargs parameter and it must be the last parameter listed.
Methods may be overloaded with vararg parameters, but beware of a problematic situation where an empty argument array or no arguments is passed - I'll explain in the example code.
Constructors may also be overloaded with vararg parameters, but beware of a problematic situation where an empty argument array or no arguments is passed - I'll explain in the example code.
A legal declaration for the main method can include varargs, for example, public static void main(String ... args)
Рекомендации по теме
Комментарии
Автор

I came from a "Conservative Religious Programming" background in C++ where Constructors were pretty sacred. So much instance initialization in modern C# and Java (and sometimes C++) is happening outside of the constructors it kind of weirds me out. So I realize I am a bit fussy about that. But using VarArgs in constructors really feels a bridge too far here. As new features get added to Java lately, they try to provide Style Guide documents to promote use of them and avoid abuse -- I wonder what one about VarArgs would say. Very well explained tho I am not a fan of VarArgs constructors. I could see passing in an actual array, but this seemed to be a case of "Sure, you can DO this, but should you ever do it?" Thanks.

jvsnyc