Domanda

A while back I was playing with methods using variable-length argument lists (java) that get defined as below

public static int[] makeArray (int... a) {
return a;
}

this is a silly program but what it will do is take in an undefined amount of integers and create an array out of them so all of the below would call on the same method

makeArray(1);
makeArray(1,2);
makeArray(1,2,3);

now what I am looking to do is create a method that will have the same effect but using arrays instead of integers. I was thinking it could maybe do this by putting the arrays into a 2d array but I am not 100% sure if this is possible as the arrays could that get added could vary in size. (maybe even for this reason it isn't possible?). But as far as I know 2d array is the only way to make an array of arrays.

I have tried (please note this isn't the actual use I have for this, I just used this to experiment to see how to do this)

public static int countArrays(int[]... a) {
return a.length;
}

and this didn't compile.

Can anyone make any suggestions?

for anyone that is interested. What I want to do is create a method that will take in X many arrays and then based on that run for loops such that it adds all the array

eg:

int[] sum = new int[a[0].length];
for (int i=0; i<a.length; i++){
for (int j=0; j<a[0].length; j++){
n[i] += a[i][j];
}}
È stato utile?

Soluzione

Not sure why you say it doesn't compile - the following example works for me (compiles and prints 2):

public static void main(String[] args) throws Exception {
    int[] i1 = new int[]{1,2,3};
    int[] i2 = new int[]{1,2,3};
    int count = countArrays(i1, i2);
    System.out.println(count);
}

public static int countArrays(int[]... a) {
    return a.length;
}

Altri suggerimenti

about the point that arrays could be differnt in size. You could use the following:

int[][] b = new int[10][];
int[] c = new int[2];
int[] d = new int[2131231];
b[0] = c;
b[1] = d;

Do not pre-define the array inner array length - that will do all the business.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top