Array Operations

CSCI 1933 – Introduction to Algorithms and Data Structures
Adriana Picoral

Common Operations on Entire Arrays

  • “Resizing” an array
  • Inverting an array
  • .toEquals(Object o)
  • How to copy an array?

Add a copy method to our ArrayCalculator class

What is the return value? What arguments do we need?

Test your solution

ArrayCalculator calcOne = new ArrayCalculator(new double[]{1, 2, 3, 4, 5});
ArrayCalculator calcFour = calcOne.copy();
System.out.println(calcFour); // 1.0 2.0 3.0 4.0 5.0
System.out.println(calcFour.equals(calcOne)); // true
calcFour.setNumber(0, 99);
System.out.println(calcFour.equals(calcOne)); // false

.copy() solution

public ArrayCalculator copy() {
  ArrayCalculator newCalc = new ArrayCalculator(new double[numbers.length]);
  for (int i = 0; i < numbers.length; i++) {
    newCalc.setNumber(i, numbers[i]);
  }
  return newCalc;
}

Copying an array

Use instance method .clone() to make a shallow copy of the entire array:

double[] numbers = new double[]{3.4, 5.5, 7.6, 10.0};
double[] otherNumbers = numbers.clone();

Copying an array

Use Arrays class method .copyOf(Type[] originalArray, int length) to copy all or some elements of the original array.

import java.util.Arrays;

double[] numbers = new double[]{3.4, 5.5, 7.6, 10.0};
double[] otherNumbers = Arrays.copyOf(numbers, 4);

Use Arrays class method .copyOfRange(Type[] originalArray, int from, int to) to copy all or some elements of the original array.

double[] moreNumbers = Arrays.copyOfRange(numbers,1, 3);

Copying an array

Use System class method .arraycopy(Type[] originalArray, int indexOriginal, Type[] destinationArray, int indexDestination) to copy over elements from one array to another:

double[] otherNumbers = new double[10];
System.arraycopy(numbers, 0, otherNumbers, 3, 4);

Copying an array

  • array.clone() instance method, creates a new array that is an exact shallow copy of the original with the same length and type
  • Arrays.copyOf(...) and Arrays.copyOfRange(...) class (static) Arrays methods, create a new array of a specified length and copies elements into it
  • System.arraycopy(...) class (static) System method, copies a specified range of elements into an existing destination array

Why does .clone() take no arguments?

Looking Back

  • To copy an object, some copy methods take one argument (typical situation)
  • When would a copy method take two arguments? (hint: think static method)
  • To clone an object, the clone() method takes no arguments (typical situation)
  • When would a clone() method take one argument? (hint: think static method)