naming arrays in a loop - java

i'm out of my league.
ok so if i can do this:
int[]teams = new int[3];
for (int i = 0; i < 3; i++)
{
teams[i] = i;
}
how do i do the similar thing but naming multiple arrays, ie
for (int i = 0; i < 3; i++)
{
int[]i = new int[3];
}
I have read you can't name an array with a variable so I can't just see how to produce arrays with different names (basically more than one) using a loop.
Thanks

You'd do the following (Java):
int teams[][] = new teams[3][3]
You'd do the following (C++):
int** teams = new int*[3];
for(int i=0; i<3; i++){
teams[i] = new int[3];
}
or you could just do
int teams[3][3];
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
teams[i][j] = //whatever you want
}
}
Edit in response to your comment below:
What you're looking for is a MultiMap. There you're going to get:
MultiMap foo = new MultiMap();
foo.put("Bob", 1);
foo.put("Bob", 2);
etc...

You can make an array of arrays (sometimes called a multidimensional array):
int [][] arr = new int[137][42];

You cannot dynamically generate variable names, but you can achieve the same effect with a Map:
//Store mappings from array name (String) to int arrays (int[])
Map<String, int[]> namedArrays = new HashMap<String, int[]>();
for (int i = 0; i < 3; i++)
{
//This is going to be the name of your new array
String arrayName = String.valueOf(i);
//Map an new int[] to this name
namedArrays.put(arrayName, new int[3]);
}
//If you need to access array called "2" do
int[] array2 = namedArrays.get("2")
The advantage of doing it this way is that you can have multiple arrays with same names as long as they are in different maps. But note that when you map two or more arrays to the same name in the same map, the previous array will be overriden (lost).

Related

Creating a multi-dimensional String array from a method array parameter

I am attempting to solve a semi-difficult problem in which I am attempting to create an array and return a 3 dimensional array based on the parameter which happens to be a 2 dimensional int array. The array I'm attempting to return is a String array of 3 dimensions. So here is the code:
public class Displaydata {
static String[][][] makeArray(int[][] dimensions) {
String myArray[][][];
for (int i = 0; i < dimensions.length; i++) {
for (int j = 0; j < dimensions[i].length; j++) {
myArray[][][] = new String[i][j][]; //getting error here.
}
}
return myArray;
}
static void printArray(String[][][] a) {
for (int i = 0; i < a.length; i++) {
System.out.println("\nrow_" + i);
for (int j = 0; j < a[i].length; j++) {
System.out.print( "\t");
for (int k = 0; k < a[i][j].length; k++)
System.out.print(a[i][j][k] + " ");
System.out.println();
}
}
}
public static void main(String[] args) {
int [][] dim = new int[5][];
dim[0] = new int[2];
dim[1] = new int[4];
dim[2] = new int[1];
dim[3] = new int[7];
dim[4] = new int[13];
dim[0][0] = 4;
dim[0][1] = 8;
dim[1][0] = 5;
dim[1][1] = 6;
dim[1][2] = 2;
dim[1][3] = 7;
dim[2][0] = 11;
for (int i = 0; i < dim[3].length;i++)
dim[3][i] = 2*i+1;
for (int i = 0; i < dim[4].length;i++)
dim[4][i] = 26- 2*i;
String[][][] threeDee = makeArray(dim);
printArray(threeDee);
}
}
As you can see from the source code, I'm getting an error when I try to create an instance of my 3-dimensional array which I'm attempting to return. I'm supposed to create a three dimensional array with the number of top-level rows determined by the length of dimensions and, for each top-level row i, the number of second-level rows is determined by the length of dimensions[i]. The number of columns in second-level row j of top-level row i is determined by the value of dimensions[i][j]. The value of each array element is the concatenation of its top-level row index with its second-level row index with its column index, where indices are represented by letters : ‘A’ for 0, ‘B’ for 1 etc. (Of course, this will only be true if the indices don’t exceed 25.) I don't necessarily know where I'm going wrong. Thanks!
You should not be initializing the array on every iteration of the loop. Initialize it once outside the loop and then populate it inside the loop.
static String[][][] makeArray(int[][] dimensions) {
String[][][] myArray = new String[25][25][1];
for (int i = 0; i < dimensions.length; i++) {
for (int j = 0; j < dimensions[i].length; j++) {
myArray[i][j][0] = i + "," + j;
}
}
return myArray;
}
I just plugged in values for the size of the first two dimensions, you will need to calculate them based on what you put in there. The 'i' value will always be dimensions.length but the 'j' value will be the largest value returned from dimensions[0].length -> dimensions[n-1].length where 'n' is the number of elements in the second dimension.
Also you will need to set up a way to convert the numbers in 'i' and 'j' to letters, maybe use a Map.
I guess you should initialize the array as
myArray = new String[i][j][]; //getting error here.
I think
myArray[][][] = new String[i][j][]; //getting error here.
should be:
myArray[i][j] = new String[5]; // I have no idea how big you want to go.
And then you can fill in each element of you inner-most array like such:
myArray[i][j][0] = "first item";
myArray[i][j][1] = "second string";
...
I think you should just change that line to:
myArray = new String[i][j][]; //look ma! no compiler error
Also, you would need to initialize myArray to something sensible (perhaps null?)

Java - making an array using for loop

Is it possible in Java to make an array in a style similar to this, i have been searching for a while and haven't found anything.
int[] foo = {
for(String arg:args)
return Integer.parseInt(arg);
};
No, but you can do this instead :
int[] foo = new int[args.length];
for(int i = 0; i < foo.length; i++) {
foo[i] = Integer.parseInt(args[i]);
}
Not exactly, but try this.
int[] foo = new int[args.length]; //Allocate the memory for foo first.
for (int i = 0; i < args.length; ++i)
foo[i] = Integer.parseInt(args[i]);
//One by one parse each element of the array.
With Java 8, it can be done like this:
int[] foo = Stream.of(args).mapToInt(str -> Integer.parseInt(str)).toArray();
Kind of... Since Java 8 we have streams which can simulate loop and allow us to do things like
int[] arr = Arrays.stream(args).mapToInt(s -> Integer.parseInt(s)).toArray();
or its equivalent using method references
int[] arr = Arrays.stream(args).mapToInt(Integer::parseInt).toArray();
int[] foo = new int[arg.length];
for (int i =0;i<args.length;i++) foo[i]=Integer.parseInt(args[i]);
With array no, but you can do something similar with List:
final String args[] = {"123", "456", "789"};
List<Integer> list = new LinkedList<Integer>(){
{
for (String arg: args){
add(Integer.parseInt(arg));
}
}
};
System.out.println(list); // [123, 456, 789]
With array you have to do the following:
int[] foo = new int[args.length];
for (int i = 0; i < foo.length; i ++) {
foo[i] = Integer.parseInt(args[i]);
}

Need Help Adding an Integer Array to an Array List in Processing

Ok... So I am in the middle of a project, and I've hit a bit of a wall. If anyone could please explain how to add an integer array to an ArrayList of integer Arrays, I would greatly appreciate it. This is in processing, the javascript version more specifically. I have tested and everything works right up to 'symbols.get(i).add(tempArray). If I print tempArray right before that line it gives me '6 10 16 10 16 20', as it should. And no, it's not just the println(symbols) statement, I also tried just 'println("blah");'and that did not show up in the output, so something is going awry at the .get line.
size(850,250);
String[] myList = new String[100];
ArrayList<Integer[]> symbols = new ArrayList<Integer[]>();
int[] tempArray = new int[];
String numbers = ("6,10,16,10,16,20\n1,25,21,13,3,15\n6,5,20,6,21,20");
myList = (split(numbers, "\n"));
int j = myList.length();
for(int i = 0; i<j; i++)
{
tempArray = int(split(myList[i], ','));
symbols.get(i).add(tempArray);
}
println(symbols);
... I have also tried the following in place of 'symbols.get(i).add(tempArray);'
for(int a = 0; a < tempArray.length(); a++)
{
symbols.get(i[a]) = tempArray[a];
}
println(symbols);
... I have also tried
for(int a = 0; a < tempArray.length(); a++)
{
symbols.get(i) = tempArray[a];
}
println(symbols);
... and
for(int a = 0; a < tempArray.length(); a++)
{
symbols[i][a] = tempArray[a];
}
println(symbols);
I'm out of guesses and tries, any help would be appreciated.
First get the Array of integer by using the get method on the ArrayList, then add [index] to specify what to add at which index of the returned Array.
symbols.get(i)[a] = tempArray[a];
There are some mistakes. The key one is that you can't add int[] to the list expecting Integer[]. Here, see the comments on the code:
void setup()
{
size(850, 250);
String[] myList = new String[100];
ArrayList<Integer[]> symbols = new ArrayList<Integer[]>();
// you can't init an array without a inintial dimension
//int[] tempArray = new int[];
int[] tempArray;
String numbers = ("6,10,16,10,16,20\n1,25,21,13,3,15\n6,5,20,6,21,20");
myList = (split(numbers, "\n"));
//length is not a method... no parenthesis here
//int j = myList.length();
int j = myList.length;
for (int i = 0; i<j; i++)
{
tempArray = int(split(myList[i], ','));
// you cant add an int[] to an Integer[] arrayList
// you gotta either change the arraylist type or convert the ints to Integers
// also just use .add(). not get().add() it's a one dimension list
symbols.add(parseArray(tempArray));
println(symbols.get(i) );
println("--");
}
}
//convenience function..
Integer[] parseArray(int[] a) {
Integer[] b = new Integer[a.length];
for (int i = 0; i<a.length; i++) {
b[i] = Integer.valueOf(a[i]);
}
return b;
}
and the other way...
void setup()
{
size(850, 250);
String[] myList = new String[100];
ArrayList<int[]> symbols = new ArrayList<int[]>();
// you can't init an array without a inintial dimension
//int[] tempArray = new int[];
int[] tempArray;
String numbers = ("6,10,16,10,16,20\n1,25,21,13,3,15\n6,5,20,6,21,20");
myList = (split(numbers, "\n"));
//length is not a method... no parenthesis here
//int j = myList.length();
int j = myList.length;
for (int i = 0; i<j; i++)
{
tempArray = int(split(myList[i], ','));
symbols.add(tempArray);
println(symbols.get(i) );
println("--");
}
}

Arraylist<String[]> how to access?

I have an ArrayList< String[] >, but how do you get String[] back to normal values?
This is what I got (of course not finished), and I want it to return an Object[][] with my values. Is it possible?
public Object[][] noName(String[] col) {
ArrayList<String[]> arrlist = new ArrayList<String[]>();
for (int i = 0; i < col.length; i++) {
arrlist.add(createColumnList(col[i]));
}
// How to get it into an Object[][]?
// Something made up..
return new Object[0][0];
}
createColumnList is just a method to create an array from different columns in a XML
It's a one-liner, actually:
return arrlist.toArray(new Object[arrlist.size()][]);
But it would be even simpler (and more efficient) to start with the array directly:
final Object[][] ret = new Object[col.length][];
for (int i = 0; i < col.length; i++) ret[i] = createColumnList(col[i]);
return ret;
Try it
final Object[][] obj = new Object[col.length][];
for (int i = 0; i < col.length; i++) obj[i] = createColumnList(col[i]);
return obj;
You just to loop and Object array to store. Here is the code to add to your comment place:
List<String[]> arrList = new ArrayList<String[]>();
Object[][] objArray = new Object[ arrList.size() ][ col.length ];
for ( int i = 0; i < arrList.size(); i++ )
objArray[ i ] = arrList.get( i );
I think that will be what you want.
First of all there is an .toArray function for Arraylist.
alternatifly you can do this.
Object[][] objarr = new Object[arrlist.size()][arrlist.get(0).length]
for(int i=0;i<arrlist.size();i++){
for(int j=0;j<arrlist.get(i).size(),j++){
objarr[i][j]=arrlist.get(i)[j];
}
}
This simply loops over every element in the array and puts them in your new array. Chance Object[][] into String[][] if you want to put it in a String array instead.
I think this should also be possible but am a bit fuzy on the rules of recasting arrays.
Object[][] objarr = new Object[arrlist.size()][];
for(int i=0;i<arrlist.size();i++){
objarr=arrlist.get(i);
}

Java multiarray updating

I have String array like this one:
String[][][][][] map = new String[9][13][2][1][1];
and when I'm trying update one fild, like this:
map[0][0][1][0][1] = "true";
every fild is updating to "true", this one:
map[0][1][1][0][1]
this one:
map[0][2][1][0][1]
why this is happening?
this is my code:
int UP = 0;
int UP_RIGHT = 1;
int RIGHT = 2;
int DOWN_RIGHT = 3;
int DOWN = 4;
int DOWN_LEFT = 5;
int LEFT = 6;
int LEFT_UP = 7;
String[][][][][] map = new String[9][13][2][1][1];
public PitchMoveHelper() {
String[][] move = {
{String.valueOf(UP), "false"},
{String.valueOf(UP_RIGHT), "false"},
{String.valueOf(RIGHT), "false"},
{String.valueOf(DOWN_RIGHT), "false"},
{String.valueOf(DOWN), "false"},
{String.valueOf(DOWN_LEFT), "false"},
{String.valueOf(LEFT), "false"},
{String.valueOf(LEFT_UP), "false"}
};
String[][] used = {{"used", "false"}};
for(int z = 0; z < 9; z++) {
for(int x = 0; x < 13; x++) {
map[z][x][0] = used;
map[z][x][1] = move;
}
}
//this.updateLeftBand();
//this.updateRightBand();
//this.updateTopBand();
//this.updateBottomBand();
map[0][0][1][0][1] = "true";
System.out.println(Arrays.deepToString(getPitchMap()));
}
Your immediate problem is that the String array stores references, not actual strings. When you say
map[z][x][0] = used;
map[z][x][1] = move;
There is a single instance of used being referenced by ALL elements [z][x][0] of map (and the same for move and [z][x][1]. Any change indexed by the 4th of 5th subscript is changing that single instance, affecting what is seen by all subscripts.
To clarify more, all the following entries in map point to the same instance:
map[0][0][0]
map[0][1][0]
.
.
map[0][12][0]
map[1][0][0]
etc.
To solve the problem you need to make a deep copy of used and move for every assignment in the loop:
for(int z = 0; z < 9; z++) {
for(int x = 0; x < 13; x++) {
map[z][x][0] = deepCopy(used);
map[z][x][1] = deepCopy(move);
}
}
Where deepCopy() makes a complete copy of the input array.
String[][] deepCopy(String [][] arr)
{
String[][] temp = new String[arr.length][];
for (int i=0; i<arr.length; i++)
{
temp[i] = new String[arr[i].length];
for (int j=0; j<arr[i].length; j++)
temp[i][j] = arr[i][j];
}
return temp;
}
The key thing you need to realize is that
int[][] example = new int[2][2];
example[1][0] = 1;
example[0] = example[1];
Does NOT COPY the second row to the first. But it makes it an ALIAS to the same memory - i.e. the row is identical to the first.
If you want to copy an array, element-per-element, use
System.arraycopy(...);
If you want to do copy an array-of-arrays, you need a deep copy.
The simplest thing for you is if you copy every single entry. This may be somewhat slower, but it is probably a concept you can easily use for now.
Again:
array2 = array1;
DOES NOT COPY array1 to array2. But it makes them one array.

Categories