0

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?

2

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.