I have a method within a class I created. Each object of the class has the property of having an an Object array, and the method returns that array. However, is there a way for me to just return the single Object from within the array when the array length is 1?
-
please provide a Minimal, Complete, and Verifiable exampleOusmane D.– Ousmane D.2018-01-13 19:52:51 +00:00Commented Jan 13, 2018 at 19:52
-
Please show us the code you have written so farTheJavaGuy-Ivan Milosavljević– TheJavaGuy-Ivan Milosavljević2018-01-13 19:54:32 +00:00Commented Jan 13, 2018 at 19:54
1 Answer
You can't. If a method is declared to return Object[], you can't return an Object. The types aren't compatible.
But you don't want to, either. It's a common anti-pattern to return null from methods that return collections. It's better to return an empty collection, that way the caller doesn't have to check for null. They can just iterate over the empty collection. Almost always the code will do the right thing anyways.
This simple loop...
for (int n: getNumbers()) {
performCalculation(n);
}
...becomes this inelegant mess:
int[] numbers = getNumbers();
if (numbers != null) {
for (int n: numbers) {
performCalculation(n);
}
}
Similarly, even if it were possible, special casing a single element would make the caller's job more complicated. They'd have to check if they got a collection or a single object and branch.