UPI Study › Courses › Data Structures and Algorithms › Free lessons › Lesson 5.4 Free with a free account
Determining Whether Two Collections Hold Identical Content
Data Structures and Algorithms · Chapter 5: ArraysSection 5.4 · lesson 19 of 878 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Data Structures and Algorithms.
Lesson complete
Earn the 3 college credits for Data Structures and Algorithms
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Copying Arrays Safely →← Rows, Columns, and Higher DimensionsNext lesson: Copying Arrays Safely →
In this lesson
Compare Java arrays by content instead of by reference.
- Distinguish reference identity from content equality for arrays
- Use Arrays.equals for flat arrays and Arrays.deepEquals for nested arrays
- Analyze the cost of an element-by-element comparison with early exit
- Handle edge cases such as nulls, doubles and arrays of custom objects
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (1,094 words). Read along, or search it.
Opening Question
Same Sheet or Same Words
Picture two sheets of paper, each carrying the same recipe. They say the same thing, and yet they're two separate sheets. Now picture one sheet, with two names written on it. Ask, are these the same, and you might mean two different things. Is it the same sheet? Or does it say the same thing? With arrays, mixing those up gives wrong answers.
Key Idea
Identity Versus Content
An array variable doesn't hold the numbers. It holds a reference, a kind of address, that leads to the array object. Here, a and b are two arrays that both hold one, two, three. And c is a copy of the variable a, so it holds the same address. Run it. a equals equals b is false: two separate objects. a equals equals c is true: one object, two names. And a dot equals b is false too. Arrays inherit the most general equals, which only compares identity, just like double equals. Only the library method, Arrays dot equals, looks inside. Same length, same value at every index: true.
How It Works
Quick Checks Before the Element Loop
Arrays dot equals makes its decisions in a set order, from the quickest answer to the slowest. Same object? Then true, at once. Is either one null? Then false, unless both are. Different lengths? False. Only then does it compare the elements, index by index, and the first pair that differs means false. The quick checks cost almost nothing, so the slow element-by-element work only happens when the arrays could really match.
Nested Arrays
Why Deep Equals Exists
A two-dimensional array is an array whose elements are references to row arrays. That matters here. Arrays dot equals checks those row references for identity, just like double equals. It sees two different inner arrays, and answers false, even though every number matches. Arrays dot deep equals goes one level further. Whenever an element is itself an array, it compares that array's content too. True. Change one number deep inside q, and deep equals notices: false.
Compile Error
Deep Equals Rejects Flat Int Arrays
Deep equals is only for arrays that hold objects, such as arrays of arrays. Hand it two flat int arrays, and it won't compile. The compiler says an int array cannot be converted to an Object array. For flat arrays, Arrays dot equals is the right tool.
Worked Example
Counting Checks in a Hand-Written Comparison
Writing the comparison yourself shows exactly what the library does, and what it costs. This method follows the same steps, and counts every element check. Identity first, then null, then the lengths. The loop gives up at the first pair that differs. That's called an early exit. The test builds two arrays of a thousand numbers, and compares them in four situations. Same object, or different lengths: the answer comes with zero element checks. A difference at index five hundred costs five hundred one checks: indexes zero through five hundred. And identical content is the expensive case. All one thousand pairs must be checked.
Cost Analysis
Where the First Difference Sits
So the work depends on where the first difference sits. Same object, a null, or different lengths: constant work, whatever the size. A first difference at index k costs k plus one checks. Identical content is the worst case: n checks, growing in step with n. And no method can do better on identical arrays. Skip even one position, and a difference could hide there. That's why the cheap checks come first.
Quick Check
A Difference in the Last Slot
Quick check. Two arrays of two thousand numbers are all zeros, except that b's last slot holds seven. A method with the same steps compares them. How many element checks does it count? Pause and predict. Two thousand. The difference sits at index nineteen ninety-nine, so every pair from zero up to it is checked: nineteen ninety-nine plus one. One check would need the difference at index zero. Nineteen ninety-nine forgets that the last pair is checked too.
Edge Cases
Nulls, Empty Arrays and Different Lengths
A comparison earns trust on the unusual inputs. Arrays of different lengths are not equal. And a null never equals an array. Two null variables count as equal. Two empty arrays are equal too, because there's no pair that could differ. The danger is calling equals on a variable that is null. There's no object to run it on, so the program stops with a null pointer exception. The static form, Arrays dot equals, never fails that way. That's one more reason to prefer it.
Decimal Quirks
Not-a-Number and Negative Zero
Decimal numbers bring two quirks. For arrays of doubles, Arrays dot equals treats two not-a-number values as equal, though double equals says they aren't. And it treats zero and negative zero as different, though double equals calls them the same. It compares the stored bit patterns, not the arithmetic values.
Object Arrays
The Element Type's Equals Decides
When an array holds objects, each slot holds a reference too. So the same two questions come back, one level down. Arrays dot equals settles it by calling equals on each pair of elements. The element type decides what equal means. String compares characters. So these strings aren't the same objects, but they are equal, and so are the arrays. Nulls inside are safe as well. The library uses a null-aware comparison. If you write the loop yourself, call Objects dot equals, not first dot equals.
Custom Types
Teaching Point What Equal Means
A type you write yourself inherits the identity version of equals. Here's a point type, with no equals of its own. Two arrays hold points with identical coordinates, and Arrays dot equals says false. Every point is a different object, and identity can't see coordinates. The fix is to teach the type what equal means. Override equals: the same object is equal, something that isn't a point never is, and otherwise compare both coordinates. Run the same test again, and it prints true. The array code didn't change at all. A type that overrides equals should also override hash code. The reason belongs with hashing, in chapter fourteen.
Quick Check
Two Outer Arrays Sharing One Row
One more check. This program makes one small row, and builds two outer arrays that each hold that same row, twice. It compares them with plain Arrays dot equals, not deep equals. What does it print? Pause and predict. It prints true. Arrays dot equals compares the rows by identity, and here every row is the very same object. False needs separate row arrays, as in the earlier grid. And the call compiles, because an array of int arrays is an array of objects.
Key Takeaways
Comparing Arrays in Summary
To sum up. Double equals and an array's own equals compare references, not content. Arrays dot equals compares length and every value. Deep equals also opens inner arrays. A hand-written comparison exits at the first difference, and needs all n checks for identical arrays. And for arrays of objects, the element type's equals decides, so your own types need one.
About Data Structures and Algorithms at UPI Study
Data Structures and Algorithms (Computer Science 251) is a self-paced online course of 87 video lessons in 17 chapters, from Java and object-oriented design to arrays, linked lists, recursion, stacks and queues, trees, heaps, hash tables, sorting and graphs. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: Discrete Math vs Data Structures and Algorithms · Intro to Java vs Data Structures and Algorithms
Why take it here
Why students take Data Structures and Algorithms with UPI Study
Where the credit goes
Universities that work with NCCRS
Data Structures and Algorithms carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Determining Whether Two Collections Hold Identical Content
How do you compare two arrays in Java?
What is the difference between Arrays.equals and Arrays.deepEquals?
How long does it take to compare two arrays?
Why does Arrays.equals return false for arrays of my own objects?
About the Data Structures and Algorithms course
How many college credits is Data Structures and Algorithms?
How much does Data Structures and Algorithms cost and what is included?
Which universities accept UPI Study credits?
How long does Data Structures and Algorithms take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Data Structures and Algorithms.
87 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →