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.
source to share
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() );
source to share
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.
source to share
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.
source to share