UPI Study › Courses › Data Structures and Algorithms › Free lessons › Lesson 5.5 Free with a free account
Copying Arrays Safely
Data Structures and Algorithms · Chapter 5: ArraysSection 5.5 · lesson 20 of 877 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: Why Connecting Nodes Solves Problems Arrays Cannot →← Determining Whether Two Collections Hold Identical ContentNext lesson: Why Connecting Nodes Solves Problems Arrays Cannot →
In this lesson
Make reference, shallow and deep copies of Java arrays without surprises.
- Distinguish reference copies, shallow copies and deep copies of arrays
- Copy arrays with clone, Arrays.copyOf, Arrays.copyOfRange and System.arraycopy
- Make deep copies of arrays of changeable objects and of two-dimensional arrays
- Prevent aliasing bugs with defensive copies
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,053 words). Read along, or search it.
Opening Question
A Backup That Got Sorted Too
This program keeps a backup of three scores, then sorts the scores, and prints the backup. Run it, and the backup comes out sorted too. Nothing touched the backup directly. So why did it change? With a single number, b equals a gives b its own copy. Arrays don't work that way, and the surprise catches nearly every beginner.
Key Idea
Reference, Shallow and Deep Copies
An array variable holds a reference, a pointer to where the array lives. Copying the variable copies only that pointer. Think of a shared online document. Send a friend the link, and you both edit the same document. That's a reference copy. Download a copy of the file, and edits no longer travel. But any links inside still lead to the same linked documents. That's a shallow copy. Download the file and everything it links to, and nothing is shared. That's a deep copy.
Aliasing
Two Names for One Array
Two variables that refer to the same array are aliases. Here, b equals a copies the reference, and no new array exists. Set b, zero, to ninety-nine, and a, zero, prints ninety-nine. And a equals equals b is true: these are the very same array. Passing an array to a method is also a reference copy. Add bonus gets a second name for the caller's marks, so its changes show up back in main. Sometimes that's exactly what you want. When it isn't, hand the method a copy.
Copying Tools
Standard Ways to Copy an Array
For arrays of plain values, like ints or doubles, any copy of the array is fully independent. Java gives several standard ways to make one. Clone duplicates the whole array. Change the clone's first slot, and the source stays as it was. Arrays dot copy of lets you pick the new length. Longer pads with zeros. Copy of range takes a slice, from a start index up to, but not including, an end. System dot array copy writes into an array that already exists: source, start, destination, where to write, and how many. Three values from index one land at index two. The last tool is a plain loop, which you can adapt to change values as you copy.
Quick Check
Copying Into an Array of Nines
Quick check. This program copies part of one array into another that's already full of nines. What does the destination hold afterward? Pause and predict. Three, four, five, nine, nine. Reading starts at index two of the source, which holds three, and writing starts at index zero of the destination. Three values are copied, and the last two nines are untouched. Two, three, four would mean reading from index one.
Shallow Copies
Shared String Builders
All of those tools make shallow copies. For plain values that's a complete copy. For objects, it isn't. Here, each slot holds a reference to a string builder, a library type whose text can change. Clone copies the slots, so both arrays point to the same objects. Append an exclamation mark through the copy, and the original's Ann shows it too. Both slots refer to that one object. But replace a slot of the copy with a new object, and only the copy changes: the original still says Raj. Strings can never change once made, so a shallow copy of a string array is safe. Adding dish builds a new string, just for the copy.
Key Rule
Changing Versus Replacing a Slot
So two kinds of change behave differently after a shallow copy. This is the key to the whole topic. Changing the object a slot refers to is seen through both arrays, because they share it. Replacing the slot with a different object is seen only in that array, because each array has its own slots.
Deep Copies
Building a New Object per Slot
To separate them completely, copy each object as well as the array. Make a new array of the same length, loop over the old one, and build a new object for each slot. New string builder of people, i, starts a fresh object with the same text. Now the append changes only the copy: Ann, and Ann with an exclamation mark. And comparing the two slots with double equals gives false: different objects. For types you write yourself, you'd give them a way to build a duplicate in the same spirit.
Two-Dimensional Arrays
Copying Every Row of a Grid
A two-dimensional array is an array of objects too: its slots refer to rows. So clone on the outer array copies the row references, not the rows. Change a number through the shallow copy, and the original grid shows ninety-nine. The cure is to copy each row as well. Make the outer array with the row count only, then clone every row into it. Now a change to the deep copy stays there. The grid still has three in row one, while the copy has seventy-seven.
Quick Check
A Grid Copied With CopyOf
One more check. A grid is copied with Arrays dot copy of. Then one whole row of the copy is replaced, and one number in another row is changed. What does the original grid print? Pause and predict. Row zero changes to one, eight. Copy of made a shallow copy, so row zero is shared, and the eight leaks across. But replacing row two only changed the copy's own slot, so the original keeps five, six. The untouched answer assumes a deep copy, and the zeros assume a reference copy.
Best Practices
Habits That Prevent Aliasing Bugs
Bugs like these, from unexpected sharing, are called aliasing bugs. They're hard to find, because the damaging line and the line that shows it can be far apart. A few habits prevent them. Decide who owns the data. Copy an array you receive and want to keep, and return a copy of one you want to protect. That's a defensive copy. Match the copy to the elements: shallow for plain values and strings, deep for changeable objects and rows. Don't copy when code only reads an array. And test with a change: change one side, and print the other.
The Fix
Repairing the Broken Backup
Back to the broken backup. The backup was just a second name, so sorting one sorted both. The fix is one call. Make the backup a clone, and it keeps the original order: ninety, seventy-five, eighty-eight.
Key Takeaways
Copying Arrays in Summary
To sum up. Assigning one array variable to another copies the reference: two names, one array. Clone, copy of, copy of range, array copy and a loop all make shallow copies. For changeable objects and two-dimensional rows, copy each element to get a deep copy. And prevent aliasing bugs with defensive copies, on the way in and on the way out.
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 Copying Arrays Safely
What is the difference between a shallow copy and a deep copy of an array?
Why does changing a copied array change the original in Java?
How does System.arraycopy work in Java?
How do you deep copy a 2D array in Java?
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 →