Evgenij Reznik
Evgenij Reznik

Reputation: 18614

What type to return?

Consider a method which produces different types of results. In my case it's either an ArrayList or an Integer (pseudo code):

int a = ... // value for a comes from another function

public ArrayList compute(){ // return either ArrayList or Integer
    if(a==1){
        ArrayList result = new Arraylist()
        for(int i=0; i<=something; i++){
            arr.add(...);   
        }    
    }
    if(a==2){
        int result;
        result = somethingElse;
    }
    return result;
}

Depending on the result of a, the result of result comes either from a loop and loads the results into an ArrayList, or in the second case it will just be a single number.

What type should the method return?

Upvotes: 0

Views: 64

Answers (3)

michael
michael

Reputation: 9799

An alternative to returning a List (but "functionally" the same),

public void compute(List<Integer> result){
    // add/remove/set the given list,
}

And although this looks like a bad design in general, you may in this case actually return a value that indicates if a "list" or a single value (a list with one element) is returned.

public boolean compute(List<Integer> result){ ...

Or, better, the length of the list (depends on what you're really trying to achieve):

public int compute(List<Integer> result){
    ...
    return result.size();
}

Upvotes: 0

Fodder
Fodder

Reputation: 584

You can change the signature of the method to be public Object compute(), so that you can return both ArrayLists and Integers, but I'm not exactly sure why you'd want to do this.

It just means that whenever you call compute(), you're going to need to check the type of the Object that you received, e.g.

Object result = compute();
if(result instanceof ArrayList) {
    // Do ArrayList stuff
} elseif(result instanceof Integer) {
    // Do Integer stuff
}

Note: Object is the super class for all objects in Java, so if there is a time where you may want to return lots of different things, you can use Object. But the better solution may be to create an Interface, if the things you're returning will have something in common.

See here: http://docs.oracle.com/javase/tutorial/java/concepts/interface.html

Upvotes: -1

Reimeus
Reimeus

Reputation: 159854

Return a List<Integer>. For a single integer simply return a list with a single element.

Upvotes: 7

Related Questions