taylorialcom/ DataStructures

Arrays

An array stores a collection of like data.

Introduction

Examples

Consider the following two methods. Both of these methods reverse the order of the elements of an array, and yet they are quite different.

public static double[] reverse1(double[] data) {
  double[] temp = new double[data.length];
  for(int i=0; i < data.length; i++){
    temp[i] = data[data.length-1-i];
  }
  return temp;
}

public static double[] reverse2(double[] data) {
  for(int i=0; i < data.length/2; i++){
    int j = data.length-1-i;
    double temp = data[i];
    data[i] = data[j];
    data[j] = temp;
  }
  return data;
}

How do reverse1() and reverse2() differ?

1

Assuming your wildest dreams are about easily adding elements to a collection of items.