JAG98 4 Share Posted November 26, 2020 int[ ][ ] myArr1 = {{1,2},{3,4},{5,6}}; How do I get myArr2 from myArr1 such that it contains all the elements of the first array with an added element {7,8}? Position of the last element doesn't matter. int[ ][ ] myArr2 = myArr1.push({7,8}) doesn't seem to work. 'cannot resolve symbol push' is the error that pops up Link to comment Share on other sites More sharing options...
TheCloakdOne 389 Share Posted November 26, 2020 int[ ][ ] myArr1 = { {1,2}, {3,4}, {5,6} }; //This array is bound to a size of 3 so you cant add to it //Create new array with +1 size for our new element int [][] myArry2 = new int[myArr1.length+1][myArr1.length+1]; //Add in our old elements from the old array for (int i = 0; i<myArr1.length; i++) { myArry2[i][0] =myArr1[i][0]; myArry2[i][1] =myArr1[i][1]; } //Add in our new entry myArry2[myArr1.length][0] = 7; myArry2[myArr1.length][1] = 8; //Print out the result list System.out.println("myArr2: "); for (int i = 0; i<myArry2.length; i++) { System.out.println(myArry2[i][0] + " - " + myArry2[i][1]); } } Probs can be done in a nicer way but should get you on your way at least. Link to comment Share on other sites More sharing options...
JAG98 4 Author Share Posted November 26, 2020 1 hour ago, TheCloakdOne said: int[ ][ ] myArr1 = { {1,2}, {3,4}, {5,6} }; //This array is bound to a size of 3 so you cant add to it //Create new array with +1 size for our new element int [][] myArry2 = new int[myArr1.length+1][myArr1.length+1]; //Add in our old elements from the old array for (int i = 0; i<myArr1.length; i++) { myArry2[i][0] =myArr1[i][0]; myArry2[i][1] =myArr1[i][1]; } //Add in our new entry myArry2[myArr1.length][0] = 7; myArry2[myArr1.length][1] = 8; //Print out the result list System.out.println("myArr2: "); for (int i = 0; i<myArry2.length; i++) { System.out.println(myArry2[i][0] + " - " + myArry2[i][1]); } } Probs can be done in a nicer way but should get you on your way at least. Yep tried this. Too cumbersome and lengthy if one might say so. Deciding to stick to the Arraylist method for now. Converting to Arraylist, then adding and converting back. If nothing else, helps avoid the for loop hassles. Thanks for the suggestion though! Link to comment Share on other sites More sharing options...
Neffarion 486 Share Posted November 26, 2020 You can use System#arraycopy public static int[][] append(int[][] matrix, int[][] suffix){ int[][] result = Arrays.copyOf(matrix, matrix.length + suffix.length); System.arraycopy(suffix, 0, result, matrix.length, suffix.length); return result; } Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.