How do you pass Array dimensions along with the Array in java?
I invision something like this:
public String[1][1] abc(){
return theStringArray
}
//but this isn't possible
So is there a way to pass dimensions of arrays?
Right now I have 2 methods that pass an int for each dimension but is there a better way of doing this?
The problem at it’s heart is this:
When I try to pass the array and find it’s length, it gives me a load of errors. The problem is that the array for the class receiving the array needs to initialize the array the the passed array will copy to, but without the passed arrays dimensions, how can I initialize it?
Class the array is passed to:
String[][] lordStats;
ArrayList<String> troopList;
public void loader() {
lord lorder = new lord();
lordStats = lorder.returnLord();
total = lorder.returnLordTotal();
for (int i = 0; i < lordStats[0].length; i++)
troopList.add (lordStats[i][2]);
}
Class the array comes from: note that method lord creator is called multipul times.
public class lord {
static int total;
String[][] lordStats;
public void total(int total1) {
total = total1;
System.out.println("lordTotal");
}
public void lordCreator(String lord, String kingdom, String troop, int times) {
lordStats = new String[total][3];
System.out.println("animalStats");
lordStats[times][0] = lord;
lordStats[times][1] = kingdom;
lordStats[times][2] = troop;
}
public String[][] returnLord() {
return lordStats;
}
In Java, you usually don’t have to pass array dimensions along with the array, since every array implicitly knows its own dimensions.
If the array is called
arr, thenarr.lengthwould return its size. Ifarris a 2D array, thenarr[0].lengthwould give the size of the first row;arr[1].lengthis the size of the next row, and so on.If the function is to allocate an array of caller-specified size, simply pass the desired dimensions into the function as
intarguments.