Arrays, cont MONDAY APRIL 6, 2015. Review from lab Deep vs Shallow copy array1array2 25.5 23 15.8...

Preview:

DESCRIPTION

Shallow copy  The reference is copied not the object itself  The two variables are called “aliases” since they both refer to the same object.  When passing objects to a method, a shallow copy is performed. (This includes arrays).

Citation preview

Arrays, contMONDAY – APRIL 6, 2015

Review from lab Deep vs Shallow copy

array1 array2

25.52315.81922

array2 = array1;

What happens?

Shallow copy The reference is copied not the object itself The two variables are called “aliases” since they both refer to the same object. When passing objects to a method, a shallow copy is performed. (This includes arrays).

Deep copy

25.52315.81922

array2 = new double[array1.length];for (int idx = 0; idx < array1.length; idx++){ array2[idx] = array1[idx];}

What happens?

array2array1

Deep copy

25.52315.81922

array2array1

25.52315.81922

Concurrent (parallel) arrays

String [] months = {“Jan”, “Feb”, “Mar”, … “Dec”}; int[] days = {31, 28, 31, … 31};

for (int ii = 0; ii < months.length; ii++) { S.O.P(months[ii] + “ has “ + days[ii] + “ days.”) } See MonthDays.java

Arrays of Objects Declare the array; Instantiate the array; Instantiate the objects of the array;

See ObjectArray.java

Now for the coolest thing ever!

VarargsDemo1.java

And the enhanced for loop

See DisplayTestScores.java

Array Methods See the Java API https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

API stands for Application Program Interface Everything you need to know to use classes in the Java libraries.

Comparing arrays Write a method, areSame, that returns true if the two arrays, array1 and array2 contain the exact same values and false otherwise.

array1 and array2 are arrays of char type.

Note: if one or the other of the arrays are null, return false. If they are both null, return true.

Sum the values Write a method, sumArray, that takes in a single array of double and returns the sum of the elements in the array.

If the array of double is null, return Double.MIN_VALUE;

Find a given value Write a java method, findString, that takes in an array of String objects and a String search key and returns an int with the location of the search key in the array.

Return -1 if the key is not found in the array.

Find the highest value Write a method, highest, which takes in an array of int and returns the largest int in the array. If the array is null or has no elements, return Integer.MIN_VALUE;

Combining arrays Write a method, arrayConcat which takes in two double arrays and returns a new array which is the first array concatenated with the second (in other words, the array will contain all of the elements of the first followed by all of the elements of the second.

It should work properly if either of the arrays is null. If both are null, the method should return null.

Recommended