
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Store a 2D Array in Another 2D Array in Java
Create an array to which you want to store the existing array with the same length. A 2d array is an array of one dimensional arrays therefore, to copy (or, to perform any operation on) the elements of the 2d array you need two loops one nested within the other. Where, the outer loop is to traverse through the array of one dimensional arrays and, the inner loop is to traverse through the elements of a particular one dimensional array.
Example
public class Copying2DArray { public static void main(String args[]) { int[][] myArray = {{41, 52, 63}, {74, 85, 96}, {93, 82, 71} }; int[][] copyArray =new int[myArray.length][]; for (int i = 0; i < copyArray.length; ++i) { copyArray[i] = new int[myArray[i].length]; for (int j = 0; j < copyArray[i].length; ++j) { copyArray[i][j] = myArray[i][j]; } } System.out.println(Arrays.deepToString(copyArray)); } }
Output
[[41, 52, 63], [74, 85, 96], [93, 82, 71]]
Advertisements