Comparing 2D arrays in Java involves checking for structural and element-wise equality; at compare.edu.vn, we provide insights and methods to accomplish this accurately. This guide will explore various approaches, from basic iteration to leveraging Java’s built-in utilities, ensuring you can effectively compare multidimensional arrays. Understanding these methods enhances your ability to manipulate and validate data structures. Discover the nuances of comparing 2D arrays, explore different comparison techniques, and find practical examples that illuminate the path to successful array comparison.
1. What is the Simplest Way to Compare 2D Arrays in Java?
The simplest way to compare 2D arrays in Java is by using the Arrays.deepEquals()
method. This method checks for deep equality, meaning it compares the contents of the arrays and any nested arrays. Here’s how to use it:
import java.util.Arrays;
public class ArrayComparison {
public static void main(String[] args) {
int[][] array1 = {{1, 2}, {3, 4}};
int[][] array2 = {{1, 2}, {3, 4}};
int[][] array3 = {{5, 6}, {7, 8}};
boolean areEqual1and2 = Arrays.deepEquals(array1, array2);
boolean areEqual1and3 = Arrays.deepEquals(array1, array3);
System.out.println("array1 and array2 are equal: " + areEqual1and2); // Output: true
System.out.println("array1 and array3 are equal: " + areEqual1and3); // Output: false
}
}
Arrays.deepEquals()
handles null checks and compares corresponding elements recursively, making it a convenient and reliable method for most use cases. For custom comparison logic or performance-critical scenarios, you may need to implement your own comparison methods, but for a quick and accurate comparison, Arrays.deepEquals()
is the best option.
2. Why is Deep Equality Important When Comparing 2D Arrays?
Deep equality is important when comparing 2D arrays because it ensures that the contents of the arrays are identical, not just the references. In Java, comparing arrays using ==
checks if both variables point to the same memory location (i.e., the same array object). This is known as reference equality. However, you often need to know if two different array objects contain the same elements in the same order, which requires a deep equality check.
Consider the following example:
int[][] array1 = {{1, 2}, {3, 4}};
int[][] array2 = {{1, 2}, {3, 4}};
System.out.println(array1 == array2); // Output: false
Even though array1
and array2
contain the same elements, array1 == array2
returns false
because they are different objects in memory. To correctly compare the contents, you need to use a method that checks deep equality, such as Arrays.deepEquals()
:
import java.util.Arrays;
int[][] array1 = {{1, 2}, {3, 4}};
int[][] array2 = {{1, 2}, {3, 4}};
System.out.println(Arrays.deepEquals(array1, array2)); // Output: true
Deep equality is particularly important in scenarios where you are dealing with data that has been copied or serialized and deserialized, as these operations create new array objects. Without a deep equality check, you might incorrectly identify arrays as different, even though they contain the same data.
3. How Does Arrays.deepEquals()
Work Internally?
Arrays.deepEquals()
method in Java works by recursively comparing the elements of the arrays. Here’s a breakdown of how it operates internally:
-
Null Check:
- First, it checks if the two input arrays are
null
. If both arenull
, it returnstrue
. If only one isnull
, it returnsfalse
.
if (a == null || b == null) return a == b;
- First, it checks if the two input arrays are
-
Type and Length Check:
- It verifies that both inputs are arrays and that they have the same length. If they are not arrays or have different lengths, it returns
false
.
int length = Array.getLength(a); if (length != Array.getLength(b)) return false;
- It verifies that both inputs are arrays and that they have the same length. If they are not arrays or have different lengths, it returns
-
Element-wise Comparison:
- It iterates through the elements of the arrays, comparing corresponding elements.
-
Recursive Deep Equality Check:
- For each pair of elements, it checks if they are arrays themselves.
- If the elements are arrays, it recursively calls
deepEquals()
to compare these nested arrays. - If the elements are not arrays, it compares them using the
equals()
method for objects or the==
operator for primitive types.
for (int i = 0; i < length; i++) { Object e1 = Array.get(a, i); Object e2 = Array.get(b, i); if (!deepEquals0(e1, e2)) return false; }
Here’s a simplified view of the recursive helper method deepEquals0()
:
private static boolean deepEquals0(Object e1, Object e2) {
if (e1 == e2)
return true;
if (e1 == null || e2 == null)
return false;
Class<?> cl1 = e1.getClass();
if (!cl1.isArray()) {
return e1.equals(e2);
}
// Array comparison
Class<?> cl2 = e2.getClass();
if (!cl2.isArray()) {
return false;
}
if (cl1.getComponentType() != cl2.getComponentType())
return false;
return deepEquals(e1, e2);
}
The recursion continues until all elements and sub-elements have been compared. If any pair of elements is not equal, the method immediately returns false
. If the entire array is traversed and all elements are equal, the method returns true
.
This approach ensures that the contents of the arrays are thoroughly compared, regardless of how deeply nested they are. The use of recursion makes Arrays.deepEquals()
a powerful tool for comparing complex, multi-dimensional arrays in Java.
4. Can You Provide an Example of Comparing 2D String Arrays in Java?
Yes, here’s an example of comparing 2D String arrays in Java using Arrays.deepEquals()
:
import java.util.Arrays;
public class StringArrayComparison {
public static void main(String[] args) {
String[][] array1 = {{"apple", "banana"}, {"orange", "grape"}};
String[][] array2 = {{"apple", "banana"}, {"orange", "grape"}};
String[][] array3 = {{"apple", "banana"}, {"kiwi", "melon"}};
boolean areEqual1and2 = Arrays.deepEquals(array1, array2);
boolean areEqual1and3 = Arrays.deepEquals(array1, array3);
System.out.println("array1 and array2 are equal: " + areEqual1and2); // Output: true
System.out.println("array1 and array3 are equal: " + areEqual1and3); // Output: false
}
}
In this example, array1
and array2
are deeply equal because they contain the same strings in the same order. However, array1
and array3
are not equal because the second row of array3
contains different strings.
5. What Are the Performance Implications of Using Arrays.deepEquals()
?
Using Arrays.deepEquals()
for comparing 2D arrays in Java provides convenience and accuracy, but it’s important to be aware of its performance implications. Here are several factors to consider:
- Time Complexity:
Arrays.deepEquals()
has a time complexity of O(N), where N is the total number of elements in the arrays being compared. This is because the method must potentially traverse every element in both arrays. In the worst case, it needs to compare each element of the first array with the corresponding element of the second array.
- Recursion Overhead:
- The method uses recursion to handle nested arrays. Each recursive call adds overhead due to function call stack management. For deeply nested arrays, this overhead can become significant.
- Early Exit:
Arrays.deepEquals()
includes an early exit optimization. If it encounters a pair of elements that are not equal, it immediately returnsfalse
without comparing the remaining elements. This can save time when the arrays differ early in the comparison process.
- Object Comparison:
- When comparing non-array elements,
Arrays.deepEquals()
uses theequals()
method of the objects. The performance of this comparison depends on the implementation of theequals()
method in the objects being compared. For custom objects with complexequals()
implementations, the comparison can be slower.
- When comparing non-array elements,
- Null Checks:
- The method performs null checks at various stages, which adds a small overhead. However, these checks are necessary to prevent
NullPointerException
and ensure correct behavior.
- The method performs null checks at various stages, which adds a small overhead. However, these checks are necessary to prevent
- Array Type:
- The type of array (e.g.,
int[][]
,String[][]
,Object[][]
) can also impact performance. Comparing primitive arrays (likeint[][]
) is generally faster than comparing object arrays (likeString[][]
) because primitive comparisons are more efficient than calling theequals()
method on objects.
- The type of array (e.g.,
Here’s a summary of the key performance considerations:
Factor | Implication |
---|---|
Time Complexity | O(N), where N is the total number of elements in the arrays. |
Recursion Overhead | Can be significant for deeply nested arrays due to function call stack management. |
Early Exit | Can improve performance by stopping the comparison as soon as a difference is found. |
Object Comparison | Performance depends on the equals() method implementation of the objects being compared. |
Null Checks | Adds a small overhead but is necessary for safety and correctness. |
Array Type | Primitive arrays are generally faster to compare than object arrays. |
To mitigate performance issues when using Arrays.deepEquals()
, consider the following:
- Use Specific Array Types: If possible, use primitive arrays (e.g.,
int[][]
,double[][]
) instead of object arrays (e.g.,Integer[][]
,String[][]
) for better performance. - Optimize
equals()
Method: If you are comparing arrays of custom objects, ensure that theequals()
method is implemented efficiently. - Manual Comparison: For performance-critical applications, consider implementing a custom comparison method that avoids recursion and provides more control over the comparison process.
- Limit Array Size: Avoid comparing extremely large arrays if possible, as the time complexity of O(N) can become a bottleneck.
While Arrays.deepEquals()
is a convenient and reliable method for most use cases, understanding its performance implications can help you make informed decisions and optimize your code for better performance.
6. How Can You Implement a Custom Method to Compare 2D Arrays?
Implementing a custom method to compare 2D arrays in Java allows you to tailor the comparison logic to your specific needs and potentially optimize performance. Here’s a step-by-step guide to creating such a method:
-
Method Signature:
- Define a method that takes two 2D arrays as input and returns a boolean value indicating whether they are equal.
public static boolean are2DArraysEqual(int[][] arr1, int[][] arr2) { // Implementation details will go here }
-
Null Check:
- Check if either of the arrays is
null
. If both arenull
, returntrue
. If only one isnull
, returnfalse
.
if (arr1 == null || arr2 == null) { return arr1 == arr2; }
- Check if either of the arrays is
-
Length Check:
- Verify that both arrays have the same number of rows and columns. If not, return
false
.
if (arr1.length != arr2.length) { return false; } for (int i = 0; i < arr1.length; i++) { if (arr1[i].length != arr2[i].length) { return false; } }
- Verify that both arrays have the same number of rows and columns. If not, return
-
Element-wise Comparison:
- Iterate through the arrays and compare corresponding elements. If any pair of elements is not equal, return
false
.
for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr1[i].length; j++) { if (arr1[i][j] != arr2[i][j]) { return false; } } }
- Iterate through the arrays and compare corresponding elements. If any pair of elements is not equal, return
-
Return True:
- If all checks pass, return
true
to indicate that the arrays are equal.
return true;
- If all checks pass, return
Here’s the complete custom method:
public class CustomArrayComparison {
public static void main(String[] args) {
int[][] array1 = {{1, 2}, {3, 4}};
int[][] array2 = {{1, 2}, {3, 4}};
int[][] array3 = {{5, 6}, {7, 8}};
boolean areEqual1and2 = are2DArraysEqual(array1, array2);
boolean areEqual1and3 = are2DArraysEqual(array1, array3);
System.out.println("array1 and array2 are equal: " + areEqual1and2); // Output: true
System.out.println("array1 and array3 are equal: " + areEqual1and3); // Output: false
}
public static boolean are2DArraysEqual(int[][] arr1, int[][] arr2) {
if (arr1 == null || arr2 == null) {
return arr1 == arr2;
}
if (arr1.length != arr2.length) {
return false;
}
for (int i = 0; i < arr1.length; i++) {
if (arr1[i].length != arr2[i].length) {
return false;
}
}
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr1[i].length; j++) {
if (arr1[i][j] != arr2[i][j]) {
return false;
}
}
}
return true;
}
}
Custom Comparison for Objects
If you are working with 2D arrays of objects, you should use the equals()
method to compare the elements:
public static boolean are2DArraysEqual(Object[][] arr1, Object[][] arr2) {
if (arr1 == null || arr2 == null) {
return arr1 == arr2;
}
if (arr1.length != arr2.length) {
return false;
}
for (int i = 0; i < arr1.length; i++) {
if (arr1[i].length != arr2[i].length) {
return false;
}
}
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr1[i].length; j++) {
if (!arr1[i][j].equals(arr2[i][j])) {
return false;
}
}
}
return true;
}
Advantages of a Custom Method
- Performance Optimization: You can optimize the comparison process based on the specific characteristics of your arrays. For example, if you know that the arrays are sorted, you can use a more efficient comparison algorithm.
- Custom Equality Logic: You can define custom equality logic for the elements in the array. For example, you might want to compare strings case-insensitively or compare floating-point numbers with a tolerance.
- Early Exit: You can implement early exit strategies to improve performance. For example, if you know that certain rows or columns are more likely to differ, you can compare those first.
- Control Over Recursion: You can avoid recursion, which can be beneficial for very large arrays where recursion depth might be a concern.
By implementing a custom method to compare 2D arrays, you gain full control over the comparison process and can tailor it to meet your specific requirements.
7. What is the Difference Between Reference Equality and Value Equality for Arrays?
In Java, the difference between reference equality and value equality is crucial when dealing with arrays. Here’s a breakdown of each concept:
-
Reference Equality:
- Reference equality checks if two variables point to the same object in memory. In the context of arrays, it determines whether two array variables refer to the exact same array object.
- You can check reference equality using the
==
operator. - If
array1 == array2
returnstrue
, it means thatarray1
andarray2
are just two different references to the same array object. Any changes made through one reference will be reflected in the other.
int[] arr1 = {1, 2, 3}; int[] arr2 = arr1; // arr2 now refers to the same array as arr1 System.out.println(arr1 == arr2); // Output: true arr1[0] = 10; System.out.println(arr2[0]); // Output: 10 (change is reflected in arr2)
-
Value Equality:
- Value equality, also known as deep equality, checks if two arrays contain the same elements in the same order. It compares the contents of the arrays, not just their memory addresses.
- To check value equality, you need to iterate through the arrays and compare corresponding elements, or use a method like
Arrays.equals()
for 1D arrays andArrays.deepEquals()
for multi-dimensional arrays.
import java.util.Arrays; int[] arr1 = {1, 2, 3}; int[] arr2 = {1, 2, 3}; // arr2 is a new array with the same elements System.out.println(arr1 == arr2); // Output: false (different objects) System.out.println(Arrays.equals(arr1, arr2)); // Output: true (same content)
Key Differences Summarized
Feature | Reference Equality | Value Equality |
---|---|---|
Operator | == |
Arrays.equals() for 1D arrays, Arrays.deepEquals() for multi-dimensional arrays, or custom methods |
Comparison | Compares memory addresses | Compares the content of the arrays |
Object Identity | Checks if variables refer to the same object | Checks if arrays have the same elements in the same order |
Usage | To determine if two variables are aliases for the same array | To determine if two arrays have the same data |
Example with 2D Arrays
import java.util.Arrays;
public class EqualityExample {
public static void main(String[] args) {
int[][] array1 = {{1, 2}, {3, 4}};
int[][] array2 = {{1, 2}, {3, 4}};
System.out.println(array1 == array2); // Output: false (different objects)
System.out.println(Arrays.deepEquals(array1, array2)); // Output: true (same content)
}
}
When to Use Which
- Use reference equality (
==
) when you need to know if two variables refer to the exact same array object. This is useful when you want to check if modifications to one variable will affect the other. - Use value equality (
Arrays.equals()
orArrays.deepEquals()
) when you need to know if two arrays have the same content, regardless of whether they are different objects in memory. This is common when comparing arrays that have been copied or serialized and deserialized.
Understanding the difference between reference equality and value equality is essential for writing correct and efficient Java code, especially when working with arrays and other mutable objects.
8. How Do You Compare 2D Arrays With Tolerance for Floating-Point Numbers?
When comparing 2D arrays of floating-point numbers, direct equality checks using ==
can be unreliable due to the way floating-point numbers are represented in computers. Instead, you should compare the numbers with a tolerance value. Here’s how to do it:
-
Define a Tolerance Value:
- Choose a small value that represents the maximum acceptable difference between two floating-point numbers for them to be considered equal. A common choice is
1e-6
(0.000001).
double tolerance = 1e-6;
- Choose a small value that represents the maximum acceptable difference between two floating-point numbers for them to be considered equal. A common choice is
-
Implement a Custom Comparison Method:
- Create a method that iterates through the 2D arrays and compares corresponding elements. Instead of using
==
, check if the absolute difference between the numbers is less than the tolerance.
public static boolean are2DArraysEqualWithTolerance(double[][] arr1, double[][] arr2, double tolerance) { if (arr1 == null || arr2 == null) { return arr1 == arr2; } if (arr1.length != arr2.length) { return false; } for (int i = 0; i < arr1.length; i++) { if (arr1[i].length != arr2[i].length) { return false; } } for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr1[i].length; j++) { if (Math.abs(arr1[i][j] - arr2[i][j]) > tolerance) { return false; } } } return true; }
- Create a method that iterates through the 2D arrays and compares corresponding elements. Instead of using
-
Usage Example:
public class FloatArrayComparison { public static void main(String[] args) { double[][] array1 = {{1.000001, 2.000002}, {3.000003, 4.000004}}; double[][] array2 = {{1.000000, 2.000000}, {3.000000, 4.000000}}; double tolerance = 1e-6; boolean areEqual = are2DArraysEqualWithTolerance(array1, array2, tolerance); System.out.println("Arrays are equal with tolerance: " + areEqual); // Output: true } public static boolean are2DArraysEqualWithTolerance(double[][] arr1, double[][] arr2, double tolerance) { if (arr1 == null || arr2 == null) { return arr1 == arr2; } if (arr1.length != arr2.length) { return false; } for (int i = 0; i < arr1.length; i++) { if (arr1[i].length != arr2[i].length) { return false; } } for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr1[i].length; j++) { if (Math.abs(arr1[i][j] - arr2[i][j]) > tolerance) { return false; } } } return true; } }
Explanation
- Tolerance Value: The
tolerance
variable defines the acceptable margin of error. If the difference between two floating-point numbers is within this tolerance, they are considered equal. - Absolute Difference: The
Math.abs()
method is used to calculate the absolute difference between the two numbers. This ensures that the comparison works regardless of which number is larger. - Custom Method: The
are2DArraysEqualWithTolerance()
method encapsulates the comparison logic, making it easy to reuse and test.
Considerations
- Choosing the Right Tolerance: The appropriate tolerance value depends on the specific application and the expected range of values. It should be small enough to catch meaningful differences but large enough to account for potential rounding errors.
- Alternative Comparison: If you need more sophisticated comparison logic, such as relative tolerance or unit in last place (ULP) comparison, you may need to use a dedicated library or implement your own comparison functions.
By comparing floating-point numbers with a tolerance, you can avoid the pitfalls of direct equality checks and ensure that your code behaves correctly when dealing with floating-point data.
9. Can You Show How to Compare 2D Arrays Ignoring Row or Column Order?
Comparing 2D arrays while ignoring row or column order requires a more complex approach than simple element-wise comparison. Here’s how you can achieve this:
Ignoring Row Order
To compare 2D arrays ignoring row order, you need to ensure that each row in the first array has a matching row in the second array, regardless of their position.
- Convert Rows to Strings or Hash Codes:
- Convert each row of the 2D array into a string or calculate a hash code for each row. This allows you to easily compare rows without considering their order.
- Store Rows in a Set:
- Store the strings or hash codes of the rows in a
HashSet
. This data structure allows you to quickly check if a row exists in the set.
- Store the strings or hash codes of the rows in a
- Compare Sets:
- Iterate through the rows of the second array and check if each row exists in the set. If all rows of the second array are found in the set, the arrays are equal ignoring row order.
Here’s an example:
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class ArrayComparisonIgnoreRowOrder {
public static void main(String[] args) {
int[][] array1 = {{1, 2}, {3, 4}};
int[][] array2 = {{3, 4}, {1, 2}};
int[][] array3 = {{5, 6}, {7, 8}};
boolean areEqual1and2 = are2DArraysEqualIgnoreRowOrder(array1, array2);
boolean areEqual1and3 = are2DArraysEqualIgnoreRowOrder(array1, array3);
System.out.println("array1 and array2 are equal (ignoring row order): " + areEqual1and2); // Output: true
System.out.println("array1 and array3 are equal (ignoring row order): " + areEqual1and3); // Output: false
}
public static boolean are2DArraysEqualIgnoreRowOrder(int[][] arr1, int[][] arr2) {
if (arr1 == null || arr2 == null) {
return arr1 == arr2;
}
if (arr1.length != arr2.length) {
return false;
}
Set<String> rowSet1 = new HashSet<>();
for (int[] row : arr1) {
rowSet1.add(Arrays.toString(row));
}
for (int[] row : arr2) {
if (!rowSet1.contains(Arrays.toString(row))) {
return false;
}
}
return true;
}
}
Ignoring Column Order
To compare 2D arrays ignoring column order, you need to ensure that each column in the first array has a matching column in the second array, regardless of their position. This is more complex because you need to extract columns from the arrays.
- Extract Columns:
- Create methods to extract columns from the 2D arrays.
- Convert Columns to Strings or Hash Codes:
- Convert each column into a string or calculate a hash code for each column.
- Store Columns in a Set:
- Store the strings or hash codes of the columns in a
HashSet
.
- Store the strings or hash codes of the columns in a
- Compare Sets:
- Iterate through the columns of the second array and check if each column exists in the set.
Here’s an example:
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class ArrayComparisonIgnoreColumnOrder {
public static void main(String[] args) {
int[][] array1 = {{1, 2}, {3, 4}};
int[][] array2 = {{2, 1}, {4, 3}};
int[][] array3 = {{5, 6}, {7, 8}};
boolean areEqual1and2 = are2DArraysEqualIgnoreColumnOrder(array1, array2);
boolean areEqual1and3 = are2DArraysEqualIgnoreColumnOrder(array1, array3);
System.out.println("array1 and array2 are equal (ignoring column order): " + areEqual1and2); // Output: true
System.out.println("array1 and array3 are equal (ignoring column order): " + areEqual1and3); // Output: false
}
public static boolean are2DArraysEqualIgnoreColumnOrder(int[][] arr1, int[][] arr2) {
if (arr1 == null || arr2 == null) {
return arr1 == arr2;
}
if (arr1.length != arr2.length || arr1[0].length != arr2[0].length) {
return false;
}
Set<String> columnSet1 = new HashSet<>();
for (int j = 0; j < arr1[0].length; j++) {
int[] column = getColumn(arr1, j);
columnSet1.add(Arrays.toString(column));
}
for (int j = 0; j < arr2[0].length; j++) {
int[] column = getColumn(arr2, j);
if (!columnSet1.contains(Arrays.toString(column))) {
return false;
}
}
return true;
}
public static int[] getColumn(int[][] array, int column) {
int[] result = new int[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i][column];
}
return result;
}
}
Combined Approach
If you need to ignore both row and column order, you can combine the above approaches. First, ignore the row order as described above. Then, for each row, ignore the column order. This can be complex and may require careful consideration of the specific requirements.
Considerations
- Performance: These methods have higher time complexity compared to simple element-wise comparison. Using hash codes can improve performance, but you need to handle potential collisions.
- Memory Usage: Storing rows and columns in sets requires additional memory, especially for large arrays.
- Element Uniqueness: These methods assume that rows and columns are unique within the array. If there are duplicate rows or columns, the comparison might not work as expected.
By using these techniques, you can compare 2D arrays while ignoring row or column order, providing more flexible comparison options for your data.
10. How Do You Compare Jagged 2D Arrays in Java?
Comparing jagged 2D arrays (arrays where each row can have a different length) in Java requires a slightly different approach compared to rectangular arrays. Here’s how you can do it:
-
Null Check:
- Check if either of the arrays is
null
. If both arenull
, returntrue
. If only one isnull
, returnfalse
.
if (arr1 == null || arr2 == null) { return arr1 == arr2; }
- Check if either of the arrays is
-
Length Check for Rows:
- Verify that both arrays have the same number of rows. If not, return
false
.
if (arr1.length != arr2.length) { return false; }
- Verify that both arrays have the same number of rows. If not, return
-
Element-wise Comparison:
- Iterate through the arrays and compare corresponding elements. Before comparing the elements in each row, check if the row lengths are equal. If any pair of elements is not equal or if the row lengths differ, return
false
.
for (int i = 0; i < arr1.length; i++) { if (arr1[i].length != arr2[i].length) { return false; } for (int j = 0; j < arr1[i].length; j++) { if (arr1[i][j] != arr2[i][j]) { return false; } } }
- Iterate through the arrays and compare corresponding elements. Before comparing the elements in each row, check if the row lengths are equal. If any pair of elements is not equal or if the row lengths differ, return
-
Return True:
- If all checks pass, return
true
to indicate that the arrays are equal.
- If all checks pass, return
Here’s the complete method:
public class JaggedArrayComparison {
public static void main(String[] args) {
int[][] array1 = {{1, 2}, {3, 4, 5}, {6}};
int[][] array2 = {{1, 2}, {3, 4, 5}, {6}};
int[][] array3 = {{1, 2}, {3, 4}, {6}};
boolean areEqual1and2 = areJaggedArraysEqual(array1, array2);
boolean areEqual1and3 = areJaggedArraysEqual(array1, array3);
System.out.println("array1 and array2 are equal: " + areEqual1and2); // Output: true
System.out.println("array1 and array3 are equal: " + areEqual1and3); // Output: false
}
public static boolean areJaggedArraysEqual(int[][] arr1, int[][] arr2) {
if (arr1 == null || arr2 == null) {
return arr1 == arr2;
}
if (arr1.length != arr2.length) {
return false;
}
for (int i = 0; i < arr1.length; i++) {
if (arr1[i].length != arr2[i].length) {
return false;
}
for (int j = 0; j < arr