eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Introduction

In this tutorial, we’ll explore how to check if two 2d arrays are equal in Java. First, we’re going to go over the problem and explore it to better understand it. This way, we’ll also understand the common pitfalls and what to look for when dealing with similar problems.

Then, we’ll go over a naive approach to better understand the concepts. Afterwards, we’ll develop a different algorithm. Further, we’ll understand how to solve this problem without using too many resources. Therefore, knowing how to properly compare 2D arrays is not only about solving programming problems.

2. Problem Definition

Comparing 2D arrays is very important in various domains of software development. Here are some domains that use 2D arrays:

  • image processing (computer vision and image manipulation)
  • game development (represent game boards, maps, or tile-based worlds)
  • artificial intelligence (machine learning algorithms – neural networks)
  • security and cryptography (some encryption algorithms use 2d arrays of bytes or integers)

Comparing 2D arrays is more challenging than comparing 1D arrays. Unlike 1D arrays, 2D arrays need us to match both rows and columns. Consequently, this adds another layer of complexity.

Furthermore, we need to consider performance – naive methods are usually resource-intensive, especially with larger arrays.

Finally, 2D arrays being nested data structures means the code is more complex and the chances of errors are increased.

First, let’s assume we have two 2d arrays with number of rows and number of columns. As a side note, in algorithmics, we usually use and to refer to rows and columns, respectively. Now, to consider these two arrays equal, multiple conditions need to be met:

  • they must have the same number of rows m
  • they must have the same number of columns n
  • corresponding elements (arr1[i][j], arr2[i][j]) need to be equal for each and j
  • special considerations: treating null values and objects

3. Naive Approach

Normally, we’d use the Arrays.deepEquals() method. This solution is great when we need an out of the box solution. In our case, its complexity is the same as the below approach, O(m*n).

Another way to approach this problem is, naturally, the first we can think of. Consequently, we’re going to go through each array and compare each element to its correspondent.

First, let’s see what this solution looks like and then, we’ll explore it in more detail:

public static boolean areArraysEqual(int[][] arr1, int[][] arr2) {
    
    if (arr1 == null || arr2 == null || arr1.length != arr2.length) {
        return false;
    }
    
    for (int i = 0; i < arr1.length; i++) {
        // check if rows have different lengths
        if (arr1[i] == null || arr2[i] == null || 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;
            }
        }
    }
    
    return true;
}

As we can see, we’re using a loop within a loop. This means the time complexity (big O notation) will be O(m*n) where and represent the number of rows and columns, respectively. Additionally, the space complexity will be O(1) because the memory needed to solve this problem doesn’t increase with the input size.

The advantages of this approach are:

  • easy to understand and implement
  • works for various-sized arrays (jagged arrays)
  • stops immediately once the first discrepancy is identified

The disadvantages are:

  • poor time complexity
  • not optimized

One important aspect is that we need to change our approach when dealing with objects. First, the != comparison won’t work for objects. Second, we’ll need to use the equals() method and make sure the objects we’re comparing have overwritten this method. Finally, we’ll also need to take into consideration null values.

4. Efficient Solution

Now, let’s think of another solution. This solution is useful for large arrays where we can accept some differences between the two arrays. 

First, we’ll need two double parameters, let’s name them similarityThreshold and samplingWeight.  Setting the similarityThreshold with a higher value allows for fewer different elements, while a smaller value allows for more different elements. On the other hand, the samplingWeight gives us control over the number of comparisons to perform.

This solution has the same time complexity of O(m*n) as the naive one in its worst case when the samplingWeight is set to its maximum.  The maximum is 1, representing 100%, and all elements are compared.

Now, let’s look at our algorithm. First, we do some basic checks to see if the references point to the same object, are null, or have different lengths:

public static boolean areArraysEqual(int[][] arr1, int[][] arr2, double similarityThreshold, double samplingWeight) {

    if (arr1 == null || arr2 == null || arr1.length != arr2.length ||
        arr1[0].length != arr2[0].length || samplingWeight <= 0 || samplingWeight > 1) {
        return false;
    }

    int similarElements = 0;
    int checkedElements = 0;

Next, we’ll calculate the sampling step based on the sampling weight:

int step = Math.max(1, (int)(1 / samplingWeight));

// Iterate through the arrays using the calculated step
for (int i = 0; i < arr1.length; i += step) {
    for (int j = 0; j < arr1[0].length; j += step) {
        if (Math.abs(arr1[i][j] - arr2[i][j]) <= 1) {
            similarElements++;
        }
        checkedElements++;
    }
}

Using this, the algorithm knows how many elements to step over before performing the next comparison. This means that the smaller the samplingWeight, the faster the algorithm will be. However, the drawback here is the smaller the samplingWeight, the bigger the chance to skip over different elements.

Finally, we divide the similar elements identified by the checked elements to calculate the similarity ratio and compare it with the previously set threshold:

    return (double) similarElements / checkedElements >= similarityThreshold;
}

5. Conclusion

In this article, we looked at how to compare two 2d arrays in Java.  Moreover, we learned the importance of this comparison and its use in various fields.

We saw that the simplest and safest way is to compare each element at each position or use the Arrays.deepEquals() method. These solutions have the highest accuracy but also perform the most steps when the arrays are identical.

Next, we’ve seen a different solution, suitable for larger data sets. This solution can be much faster but with poorer accuracy. It’s up to us to determine which solution fits our needs.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)