Copying Arrays Safely, Explained

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

← Determining Whether Two Collections Hold Identical ContentNext lesson: Why Connecting Nodes Solves Problems Arrays Cannot →

Earn 3 college credits for Data Structures and AlgorithmsRecommended for credit by NCCRS · Computer Science 251 · self-paced · one payment, lifetime access

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.

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

How programs store and search dataData Structures and Algorithms teaches how to organize data and measure how fast code runs: arrays, linked lists, stacks, queues, trees, heaps, hash tables, sorting and graphs, all written in Java. It is a core course in computer science and software degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
A shallow copy creates a new array whose slots hold the same values or references as the original, so any objects are shared between the two arrays. A deep copy also copies each object, so nothing is shared. For arrays of int or double, a shallow copy is fully independent, but for arrays of changeable objects, such as StringBuilder objects or row arrays, only a deep copy is.
Why does changing a copied array change the original in Java?
Writing b = a copies only the reference, so a and b become two names for the same array, and a change through either one shows in both. Passing an array to a method works the same way. To get an independent array of plain values, make a real copy instead, such as int[] b = a.clone(); or int[] b = Arrays.copyOf(a, a.length);.
How does System.arraycopy work in Java?
System.arraycopy copies elements into an array that already exists. Its arguments are the source array, the start index in the source, the destination array, the index where writing begins, and the number of elements to copy. For example, System.arraycopy(src, 2, dest, 0, 3); copies src[2] through src[4] into dest[0] through dest[2], leaving the rest of dest untouched.
How do you deep copy a 2D array in Java?
Create the outer array with only the row count, then clone every row into it: int[][] copy = new int[grid.length][]; followed by a loop that runs copy[r] = grid[r].clone(); for each row. Calling clone on the outer array alone copies just the row references, so changing a number through that copy would also change the original grid.

About the Data Structures and Algorithms course

How many college credits is Data Structures and Algorithms?
Data Structures and Algorithms (Computer Science 251) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Data Structures and Algorithms cost and what is included?
$250, paid once, with lifetime access: all 87 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Data Structures and Algorithms take?
It is self-paced with no deadlines. The 87 lessons total about 15 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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.

Data Structures and Algorithms
3 credits · NCCRS
Enroll →