Saturday 18 May 2019

Dynamic or Anonymous arrays in Java

As a Java developer, many might have encountered a silly problem which is very trivial to solve!

I have one variable or may be two. And there is some kind of processing to be done, of they need to be passed to a method as an input. Also assume that there exists a method(function) that could be reused. All good! But there is a minor problem if the method accepts only an array.

What is a the best way to solve this problem?

Creating an array which need not be us d further in the caller code could be polluting the code. A better way could be to create an array and just use it for calling the method alone.

How to do that?

Easy. Just try this:

new String()[]{variable 1, variable 2}

// Assuming the variables are of string type!

😇

No comments:

Post a Comment