25
Mo re Arrays Array Review Value/Reference Semantics Arrays as Parameters Arrays as Return Values Array Traversal Algorithms Comparing Arrays Java Arrays Class

Array Review - NCSU

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Array Review - NCSU

More Arrays

Array Review

Value/Reference Semantics

Arrays as Parameters

Arrays as Return Values

Array Traversal Algorithms

Comparing Arrays

Java Arrays Class

Page 2: Array Review - NCSU

Array Review• Declaration:

– type[] name = new type[length];

• Accessing:– name[index] = value;

• An array's length field stores its number of elements.– name.length

for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " ");

}

• Zero-based indexing:– Legal indexes: between 0 and the array's length - 1.

• traversal:– An examination of each element of an array.

for (int i = 0; i < array.length; i++) {

do something with array[i];}

Page 3: Array Review - NCSU

Value semantics (primitives) value semantics: Behavior where values are copied when

assigned to each other or passed as parameters.

When one primitive variable is assigned to another, its value is copied.

Modifying the value of one variable does not affect others.

x

y

3Copyright 2008 by Pearson Education

int x = 5;

int y = x; // x = 5, y = 5

y = 17; // x = 5, y = 17

x = 8; // x = 8, y = 17

Page 4: Array Review - NCSU

Reference semantics (objects)

reference semantics: Behavior where variables actually store the address of an object in memory.

When one reference variable is assigned to another, the object is not copied; both variables refer to the same object.

Modifying the value of one variable will affect others.

int[]

int[]

a2[0]

a1 = {4, 5, 2, 12, 14, 14, 9};

a2 = a1; // refer to same array as a1

= 7;

System.out.println(a1[0]); // 7

4

index 0 1 2 3 4 5 6

valuea2

a1

4Copyright 2008 by Pearson Education

7 5 2 12 14 14 9

Page 5: Array Review - NCSU

Arrays and Methods

• Arrays can be passed as parameters

• Arrays can be returned from methods

• Arrays are objects – use reference semantics

– When an array is passed as a parameter, the arrayis not copied. The same array is shared by theoriginal variable and the parameter.

– Changes made to arrays passed as parameters to methods will be reflected in the original array

5

Page 6: Array Review - NCSU

6Copyright 2008 by Pearson Education

Array parameter examplepublic static void main(String[] args) {

int[] iq = {126, 84, 149, 167, 95};

double avg = average(iq);

System.out.println("Average = " + avg);

}

public static double average(int[] array) {

int sum = 0;

for (int i = 0; i < array.length; i++) {

sum += array[i];

}

return (double) sum / array.length;

}

Output:Average = 124.2

Page 7: Array Review - NCSU

Passing Arrays• KEY POINT: When an array is passed as aparameter to a method, the method has the ability to change the contents of the array.

public static void main(String[] args) { int[] grades = {78, 85, 64, 99, 92, 83};incrementAll(grades); System.out.println(grades[0]);

}

array[i]++;

}}

7

[0] [1] [2] [3] [4] [5]

grades

array

public static void incrementAll(int[] array) {

for (int i = 0; i < array.length; i++) {

78 85 64 99 92 83

Page 8: Array Review - NCSU

Arrays as return types (declaring)

public static type[] methodName(parameters){

• Example:

public static int[] getArrayFromUser(int length) {

int[] array = new int[length];

Scanner console = new Scanner(System.in);

for (int i = 0; i < array.length; i++) {

System.out.print("Element " + i + " (Integer): ");

while(!console.hasNextInt()){

console.next();

System.out.println("Not an integer!");

System.out.print("Element " + i + " (Integer): ");

}

array[i] = console.nextInt();

}

return array;

}

Page 9: Array Review - NCSU

Arrays as return types (calling)

type[] name = methodName(parameters);

• Example:

public static void main(String[] args) {

int[] fromUser = getArrayFromUser(5);

}

Page 10: Array Review - NCSU

Array Traversal Algorithms

• Printing an array

• Finding a value in an array

• Replacing values in an array

• Reversing an array

Page 11: Array Review - NCSU

Printing an Array

/*** Prints the contents of an array* @param data the array to print*/public static void printArray(int [] data) {

String out = "[" + data[0];for (int i = 1; i < data.length; i++) {

out += ", " + data[i];}out += "]"; System.out.println(out);

}

Page 12: Array Review - NCSU

Finding a Value in an Array/**

* Returns the index of the given value in the given array* or -1 if the value is not in the array* @param array array of values to search* @param value value to search for* @return the index of the value or -1 if the value is not* in the array*/public static int indexOf(int [] array, int value) {

for (int i = 0; i < array.length; i++) {if (array[i] == value) {

return i;}

}return -1;

}

Page 13: Array Review - NCSU

Replacing Values in an Array

/*** Replaces all occurrances of the first given value in the given* array with the second given value.* @param array array of values to search* @param val1 value to be replaced* @param val2 value to replace with*/

public static void replaceAll(int [] array, int val1, int val2) { for (int i = 0; i < array.length; i++) {

if (array[i] == val1) { array[i] = val2;

}}

}

Page 14: Array Review - NCSU

Reversing an Array

• Plan:

– Swap first and last elements

– then second and second to last elements

– Continue until you reach the middle

• Need to discuss correct way to swap values

Page 15: Array Review - NCSU

Swapping primitive values

15

Copyright 2006 by Pearson Education

◼ Consider the following code to swap two int variables:

public static void main(String[] args) {

int a = 7;

int b = 35;

System.out.println(a

// swap a with b

+ " " + b);

System.out.println(a + " " + b);

}

◼ What is wrong with this code? What is its output?

a = b;

b = a;

Page 16: Array Review - NCSU

Swapping, corrected

16

Copyright 2006 by Pearson Education

◼ When swapping, you should set aside one variable's value into a temporary variable, so it won't be lost.

◼ Better code to swap two int variables:

public static void main(String[] args) {

int a = 7;

int b = 35;

System.out.println(a + " " + b);

// swap a with b

a;int temp =

System.out.println(a + " " + b);

}

a = b;

b = temp;

Page 17: Array Review - NCSU

A swap method?

17

Copyright 2006 by Pearson Education

◼ Swapping is a common operation, so we might want to make it into a method.

◼ Does the following swap method work?

public static void main(String[]

Why or why not?

args) {

int a = 7;

int b = 35;System.out.println(a + " " + b);

// swap a

swap(a, b);

with b

int temp = a;

a = b;

b = temp;

}

System.out.println(a + " " + b);

}

public static void swap(int a, int b) {

Page 18: Array Review - NCSU

18

An array element swap method/**

* Swaps the element at the first given index in the given* array with the element at second given index.* @param array array of values* @param idx1 index of first element to be swapped* @param idx2 index of second element to be swapped*/

public static void swap(int [] array, int idx1, int idx2) { int temp = array[idx1];array[idx1] = array[idx2]; array[idx2] = temp;

}

Page 19: Array Review - NCSU

Now Reverse an Array

/*** Reverses the elements in the given array* @param array array of values to reverses*/

public static void reverse(int [] array) { for (int i = 0; i < array.length / 2; i++) {

swap(array, i, array.length - 1 - i);}

}

Page 20: Array Review - NCSU

Comparing Arrays• Arrays are objects, so we can’t use == to test for equality

– Equality is defined as two arrays containing the same values in thesame order

[0] [1] [2] [3] [4] [5]

20

grades2

grades3

[0] [1] [2] [3] [4] [5]grades1

public static void main(String[] args) {

int[] grades1 = {78, 85, 64, 99, 92, 83};

int[] grades2 = {78, 85, 64, 99, 92, 83};

int[] grades3 = grades1;}

• Is grades1 == grades2?

• Is grades1 == grades3?

78 85 64 99 92 83

78 85 64 99 92 83

Page 21: Array Review - NCSU

Array Comparison Algorithm

• Write a method that compares two arrays and returns true if the arrays are equal

public static boolean equals(int[] array1, int[] array2 {

if (array1.length != array2.length) {

return false;

}

for (int i = 0; i < array1.length; i++) {

if (array1[i] != array2[i]) {

return false;

}

}

return true;

}

Page 22: Array Review - NCSU

In-class Exercise• Go to the moodle page and work on the intArrayAlgorithms.java assignment.

Use the starter file: IntArrayAlgorithms.java. Add the following methods to the IntArrayAlgorithmsprogram:

•Exercise 7.1 - lastIndexOf: Write a method called lastIndexOf that accepts an array of integers and an integer value as its parameters and returns the last index at which the value occurs in the array. The method should return -1 if the value is not found. For example, in the array [74, 85, 102, 99, 101, 85, 56], the last index of the value 85 is 5. For this example, your program should print: The last index of the value 85 in {74, 85, 102, 99, 101, 85, 56} is 5.

•Exercise 7.2 - range: Write a method called range that returns the range of values in an array of integers. The range is defined as 1 more than the difference between the maximum and minimum values in the array. For example, if an array called list contains the values [36, 12, 25, 19, 46, 31, 22], the call of range(list) should return 35 (46 - 12 + 1). You may assume that the array has at least one element. For this example, your program should print: The range of {36, 12, 25, 19, 46, 31, 22} is 35.

•Exercise 7.3 - countInRange: Write a method called countInRange that accepts an array of integers, a minimum value, and a maximum value as parameters and returns the count of how many elements from the array fall between the minimum and maximum (inclusive). For example, in the array [14, 1, 22, 17, 36, 7, –43, 5], for minimum value 4 and maximum value 17, there are four elements whose values fall between 4 and 17. For this example, your program should print:In the array {14, 1, 22, 17, 36, 7, -43, 5}, there are 4 elements whose values fall between 4 and 17.

Your main method should create arrays to pass into the methods you write and print any results with context as shown in red. Comment out the calls to the getArrayFromUser() and getRandomArray() methods.

Use the given arrayAsString method to print array contents.

Page 23: Array Review - NCSU

22Copyright 2008 by Pearson Education

The Arrays class

Class Arrays in package java.util has useful static

methods for manipulating arrays:

Method name Description

binarySearch(array, value) returns the index of the given value in a sorted array (< 0 if not found)

equals(array1, array2) returns true if the two arrays

contain the same elements in the

same order

fill(array, value) sets every element in the array to have the given value

sort(array) arranges the elements in the array into ascending order

toString(array) returns a string representing the array, such as "[10, 30, 17]"

Page 24: Array Review - NCSU

Most Useful Arrays Methods

System.out.println(Arrays.toString(list));

– prints the array contents nicely

[17, -2, 5, 6, 8]

Arrays.equals(list1,list2)

-- compares two arrays for equality and returns a boolean

Page 25: Array Review - NCSU

In- class Exercise• Go to the moodle page and work on the

SwappingPairs.java assignment.

Within a program SwappingPairs.java, write a method called swapPairs that: • accepts an array of integers and • swaps the elements at adjacent indexes. That is, elements 0 and 1 are swapped, elements 2 and 3 are swapped, and so on. If the array has an odd length, the final element should be left unmodified.

• Your main method should create test arrays and call the swapPairs method (once for each test array). Test both even and odd length arrays.For example, the array [10, 20, 30, 40, 50] should become[20, 10, 40, 30, 50] after a call to your method with the unswapped arrayas a parameter.

• Use the Arrays.toString() method to print each test array in your main method both before and after calling the swapPairs method.