SteelReed

Search

Search posts, questions…

Java CoreQuestion 10 / 43

Junior

Java arrays: how do length, length() and size() differ? What is a shallow copy, and how are 2D arrays stored?

Short answer

Arrays use length (a field), String uses length(), collections use size(). Every built-in way to copy an array is a shallow copy.

copies only the outer arrayrows are sharedgrid: int[][]row 0: {1, 2}row 1: {3, 4}grid.clone()

3 points to say:

  1. Shallow copy: only the outer shell is copied, the elements are shared.
  2. A 2D array is an array of arrays, copy each row.
  3. Print with Arrays.toString, compare with Arrays.equals.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.