0

I have a homework task where I am required to write only 1 method (a member of class MainClass) which creates simultaneously more than one type of array -with only using this method. I tried to create a method that returns the corresponing type but then it can only be done with one type of array (see the commented code /function/). My question is how can I create sort of a templated function which returns all types at once my attemp is below, /but sadly not working/?

   import java.lang.reflect.Array;
import java.sql.SQLOutput;
import java.util.Arrays;

public class MainClass {
    //ще направим отделни методи за класовете
/*public int [] returnArr(){
    int [] ar = new int[10];
    return ar;
}*/
public void createArray(){
    //here I create more than one type of array:
    int []ar = new int[10];
    String[] str  = new String[10];
    double [] dbl  = new double[10];
}
}
class Test{
    public static void main(String[] args) {
        MainClass mcl = new MainClass();
       /*int [] ia = mcl.returnArr();
        for (int i = 0;i<10;i++){
            Arrays.fill(ia,0,9,8);
        }*/
       mcl.createArray();
       //here the ar[] array is not accessible
        Arrays.fill(ar,0,9,0);
       for (int i:ar){
           System.out.println(i);
       }
    }
}

1 Answers1

0

I hope you are practicing OOPs. In Java , its not possible for a method to return multiple types. You have mentioned, you need to create multiple types of arrays using a single method. You can go by 2 methods here.

  1. The Object oriented way - use the instance variables & initialize them in one method. It would be something like below

    public class MainClass {

    private int[] intArray;
    private String[] strArray;
    private double[] dblArray;
    public void createArray() {
        this.intArray = new int[10];
        this.strArray = new String[10];
        this.dblArray = new double[10];
    }
    

    }

And then you can use some getter methods to access the arrays.

  1. Return array of arrays - You can return multiple values as a composite type array. For example array of java.lang.Object. Since Object is the parent class of everything in Java, an array of Object can hold any types. then your method would look like
 public Object[] createArray() 
      {
      int[] intArray = new int[10];
      String[] strArray = new String[10];
      double[] dblArray = new double[10];
      Object[] returnArray = new Object[] { this.intArray, this.strArray, this.dblArray };
      return returnArray;
     }

Now in the Object array that is returned

Object[] arrays = mcl.createArray();

// arrays[0] is an integer array, arrays[1] is string array and so on.
int[] arr = arrays[0];

Now you can use the arrays in the manner you need. Hope you are clear on the concept.

Kris
  • 8,680
  • 4
  • 39
  • 67