简体   繁体   中英

How do I make an array method return a single object when the array length is 1?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM