Return two different objects from a single method in Java

Viewed 1590

Hi I am trying to return two array, 1 as string and another as float; return both i searched on net it was confusing, i am new to oops

public String[][]  loadcost(String[][] arr2, int tcount) {

        int f1 = 1;
        int f2 = 0;
        int[] costarr = null ;


        while (f2 < tcount){

            arr2[f1][f2] = cost.nextLine();
            costarr[f2] = Integer.parseInt (arr2[f1][f2]);
            f2 = f2 + 1;                            
        }

        Arrays.sort(costarr);
        return arr2 , costarr ;

my original request is to sort an 2-d array, it dint work with the code what i got on net

BBB 444 DDD 098 FF 19.01

would like to sort using the second column

4 Answers

You need to create a object containing two arrays of whatever type you want and then return that from this method as methods can only return one object.

class MyObjectName {
  String[] stringArray;
  Float[] floatArray;
}

public MyObjectName loadcost(String[][] arr2, int tcount) {
   .....
}

Hope that helps.

Use a wrapper class to wrap the two arrays, and return that:

public class Wrapper {
    public final String[] strings;
    public final float[] floats;

    public Wrapper(String[] strings, float[] floats) {
        this.strings = strings;
        this.floats = floats;
    }

}

Your method would then have a return type of Wrapper and would return a new Wrapper(arr2, costarr):

public Wrapper  loadcost(String[][] arr2, int tcount) {

        int f1 = 1;
        int f2 = 0;
        float[] costarr = null ;


        while (f2 < tcount){

            arr2[f1][f2] = cost.nextLine();
            costarr[f2] = Float.parseFloat (arr2[f1][f2]);
            f2 = f2 + 1;                            
        }

        Arrays.sort(costarr);
        return new Wrapper(arr2, costarr)
}

(By the way, I made costarr of type float[] rather than int[].)

You could then access the wrapped arrays with:

wrapper.floats //float array
wrapper.strings //String array
public class myarrayl {

        String [][] arr;
        int [] costarr;

    }

        public myarrayl loadcost(String[][] arr2, int tcount) {

            int f1 = 1;
            int f2 = 0;
            int[] costarr = null ;
            myarrayl content = null;    

            while (f2 < tcount){

                arr2[f1][f2] = cost.nextLine();
                costarr[f2] = Integer.parseInt (arr2[f1][f2]);
                f2 = f2 + 1;

            }

            Arrays.sort(costarr);
            content.arr = arr2;
                    content.costarr = costarr;
            return content;

    }

to access

Related