Katherine
Katherine

Reputation: 257

Is it possible to return multiple items in my methods?

I have written three methods of different Big-O complexities. Is there a way to return multiple values in my method without affecting the complexity? Thanks in advance!

public static double Nsquare(double[] ar){
    double max=0, difference=0; 
    double maxelement=0, minelement=0 ;
    for (int i=0; i<ar.length;++i){
        for (int j=0; j<ar.length;++j){
            difference=Math.abs(ar[i]-ar[j]);
            if (difference>max){
                max=difference;
                maxelement=ar[i];
                minelement=ar[j];
            }
        }
    }
    //return maxelement;
    //return minelement;
    return max;
}
// O(n*log(n))
public static double NlogN(double[] ar){
    Arrays.sort(ar);
    double max=ar[ar.length-1];
    double min=ar[0];
    double difference=max-min;
    //return max;
    //return min;
    return difference;
}
// O(n)
public static double N(double[] ar){

    double max = Double.NEGATIVE_INFINITY;
    double min = Double.POSITIVE_INFINITY;

    for(double x: ar){
        if(min > x) {min =x;}
        if(max < x) {max =x;}
    }
    //return max;
    //return min;
    return Math.abs(max-min); 
}

Upvotes: 2

Views: 63

Answers (3)

Nitin Dandriyal
Nitin Dandriyal

Reputation: 1607

Just write a new class with fields max, maxelement, minelement. Set this class as the return type.

class Answer{
    private double max;
    private double maxelement;
    private double minelement;
    public Answer(double max, double maxelement, double minelement){
         this.max = max;
         this.maxelement = maxelement;
         this.minelement = minelement;
    }

    public double getMax() {
        return max;
    }
    public double getMaxelement() {
        return maxelement;
    }
    public double getMinelement() {
        return minelement;
    }
}

And return like this:

public static Answer Nsquare(double[] ar){
       --
       your code
       --
       return new Answer(max, maxelement, minelement);
}

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

In java you cannot return multiple values separately. What you could do is, you could add all the values to be returned to a list and then return the reference to the list.

Something like this :

List<Double> doubleList = new ArrayList<>();
doubleList.add(max);  // index 0
doubleList.add(maxelement); // index 1
doubleList.add(minelement);  // index 2

return doubleList;

You will have to change the method signature and how this method is called.

Upvotes: 1

Shubhangi Shinde
Shubhangi Shinde

Reputation: 61

No its not possible to return multiple items. but you can create an object of those many items and you can return that.

Upvotes: 3

Related Questions