Set variable from array directly to variable list in Java

I have a Java method that returns an array of doubles. Then I would like to store these values โ€‹โ€‹in separate variables in the calling function. Is there an elegant way to do this in Java.

I could write it like:

double[] returnValues = calculateSomeDoubles();
double firstVar  = returnValues[0];
double secondVar = returnValues[1];

      

I'm just wondering if there is a way to compress this to one line? Something like:

(firstVar, secondVar) = calculateSomeDoubles();

      

This type of thing is pretty straightforward when scripting, but Java's stronger set means it's probably not possible.

0


source to share


4 answers


In principle, no, this is impossible.

You will need to return an object containing values.



MyObject myObject = calculateMyObject();

      

+5


source


The only way to use reflection is if you know in advance how many elements the calculateSomeDouble method will return.

You may need to change this . But as you can see there is more code there.

So the question is? Do you want this for automated stuff? Or save development time (no copy / paste needed)?

If you want to automate some task (for example, fill an object at runtime), then you should make a call to reflection and write a method.



You will need to set the value, not just print it.

The client call should look like

 SomeUtility.fill( myObject , withDoublesFromMethod() );

      

+1


source


If you don't have the fact that you will get 2 double values โ€‹โ€‹back, you can call the method call metode from the link

void methode(double[] array)

      

You can send an array of length 2 and put the values โ€‹โ€‹in the method.

Or, you return a collection if the return values โ€‹โ€‹might change.

List methode()

      

I am not a friend of return values โ€‹โ€‹like

double[] methode()

      

When you use Lists or Collections, the method is used as static as you are handling arrays. You can use the method better in other projects.

+1


source


My first instinct is to question your motivation to do something like this. If you have a bunch of related doubles in your program, why don't you store them in the list?

If you were, you could do something like this:

List<Double> myVars = Arrays.asList(calculateSomeDoubles());

      

But if you have to store them in separate variables, it cannot be done cleanly on one line. I advise you not to use some of the suggested reflection based solutions. It would probably be much easier to just write out your appointments on multiple lines, as you first suggested.

0


source







All Articles