# The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Arrays and ArrayLists C H A P T E R 1 1 1 slides partially adapted from.

## Presentation on theme: "The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Arrays and ArrayLists C H A P T E R 1 1 1 slides partially adapted from."— Presentation transcript:

The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Arrays and ArrayLists C H A P T E R 1 1 1 slides partially adapted from UW CSE 142 course slides Lecture Slides, Part II -- Review

Comp 101 | Özyeğin University2 A named, ordered collection of variables of identical type We do not name every individual element in the collection Instead, we give a name to the whole collection We access individual elements in the collection by specifying its order in the collection –This is called the index Recap: Arrays

3 int score = 0; int[] scores = new int[10]; 012345678 0000000000 9 scores 0 score Element type Length index

Acessing Arrays 012345678 0000000000 9 scores int[] scores = new int[10]; 012345678 25000000000 9 scores scores[0] = 25; 012345678 251700000000 9 scores scores[1] = 17; 4

Array Length int[] scores = new int[10]; println("Length of the array is " + scores.length); Length of the array is 10 5

Exercise CS 101 | Özyeğin University6 Guess the output of the following program int[] numbers = new int[5]; for (int i = 0; i < numbers.length; i++) { numbers[i] = numbers.length - i; } for (int i = 0; i < numbers.length; i++) { print(numbers[i] + " "); }

Exercise CS 101 | Özyeğin University7 Guess the output of the following program int[] numbers = new int[5]; for (int i = 0; i < numbers.length; i++) { numbers[i] = numbers.length - i; } for (int i = 0; i < numbers.length; i++) { print(numbers[i] + " "); } 5 4 3 2 1

Exercise CS 101 | Özyeğin University8 Write a program that provides a solution for the motivating example: –Get a set of numbers from the user –Print out the numbers that are above the average of the whole set of numbers

CS 101 | Özyeğin University9 int noOfNumbers = readInt("Enter the total amount of numbers: "); int[] numbers = new int[noOfNumbers]; for (int i = 0; i < numbers.length; i++) { numbers[i] = readInt("Enter a number: "); } int total = 0; for (int i = 0; i < noOfNumbers; i++) { total = total + numbers[i]; } double average = (double) total / numbers.length; for (int i = 0; i < numbers.length; i++) { if(numbers[i] > average) { println(numbers[i] + " is above average!"); }

An array is a collection of variables Each element can be used wherever a simple variable of that type is allowed. –Assignment, expressions, input/output An entire array can’t be treated as a single variable –Can’t assign or compare arrays using =, <, … –Can’t use println to read or write an entire array –But, you can do these things one element at a time Technicalities

Internal Representation of Arrays Arrays in Java are implemented as objects, which means that they are stored in the heap. The value stored in an array variable is simply a reference to the actual array. int score = 0; int[] scores = new int[10]; 0 score 012345678 0000000000 9 scores 11

Internal Representation of Arrays int score = 5; int foo = score; foo++; println(score); // prints 5 println(foo); // prints 6 5 score foo 12

Internal Representation of Arrays int score = 5; int foo = score; foo++; println(score); // prints 5 println(foo); // prints 6 5 score 5 foo 13

Internal Representation of Arrays int score = 5; int foo = score; foo++; println(score); // prints 5 println(foo); // prints 6 5 score 6 foo 14

Internal Representation of Arrays int score = 5; int foo = score; foo++; println(score); // prints 5 println(foo); // prints 6 5 score 6 foo 15

Internal Representation of Arrays int[] scores = new int[10]; int[] numbers = scores; numbers[5] = 42; println(scores[5]); // prints 42 println(numbers[5]); // prints 42 scores[0] = 77; println(scores[0]); // prints 77 println(numbers[0]); // prints 77 012345678 0000000000 9 scores numbers 16

Internal Representation of Arrays 012345678 0000000000 9 scores numbers int[] scores = new int[10]; int[] numbers = scores; numbers[5] = 42; println(scores[5]); // prints 42 println(numbers[5]); // prints 42 scores[0] = 77; println(scores[0]); // prints 77 println(numbers[0]); // prints 77 17

Internal Representation of Arrays 012345678 00000420000 9 scores numbers int[] scores = new int[10]; int[] numbers = scores; numbers[5] = 42; println(scores[5]); // prints 42 println(numbers[5]); // prints 42 scores[0] = 77; println(scores[0]); // prints 77 println(numbers[0]); // prints 77 18

Internal Representation of Arrays 012345678 00000420000 9 scores numbers int[] scores = new int[10]; int[] numbers = scores; numbers[5] = 42; println(scores[5]); // prints 42 println(numbers[5]); // prints 42 scores[0] = 77; println(scores[0]); // prints 77 println(numbers[0]); // prints 77 19

Internal Representation of Arrays 012345678 770000420000 9 scores numbers int[] scores = new int[10]; int[] numbers = scores; numbers[5] = 42; println(scores[5]); // prints 42 println(numbers[5]); // prints 42 scores[0] = 77; println(scores[0]); // prints 77 println(numbers[0]); // prints 77 20

Internal Representation of Arrays 012345678 770000420000 9 scores numbers int[] scores = new int[10]; int[] numbers = scores; numbers[5] = 42; println(scores[5]); // prints 42 println(numbers[5]); // prints 42 scores[0] = 77; println(scores[0]); // prints 77 println(numbers[0]); // prints 77 21

Individual array elements can be used as parameters, just like other simple variables. The corresponding element in the array is copied to the argument Example: int result = power(numbers[0], numbers[1]); println(numbers[0] + “ to the power ” + numbers[1] + “ is ” + result) ; Array elements as arguments

Array arguments (entire arrays) work differently: –An array is never copied –The array name is always treated as a reference to the collection of elements Whole arrays as arguments

Initializing Arrays Java makes it easy to initialize the elements of an array as part of a declaration. The syntax is type [] name = { elements }; where elements is a list of the elements of the array separated by commas. The length of the array is automatically set to be the number of values in the list. For example, the following declaration initializes the variable powersOfTen to the values 10 0, 10 1, 10 2, 10 3, and 10 4 : int[] powersOfTen = { 1, 10, 100, 1000, 10000 }; This declaration creates an integer array of length 5 and initializes the elements as specified. 24

Exercise Comp 101 | Özyeğin University25 Write a method, which takes an array of integers as argument and returns an array with the same elements in reverse order.

The ReverseArray Program skip simulation public void run() { int n = readInt("Enter number of elements: "); int[] intArray = createIndexArray(n); println("Forward: " + arrayToString(intArray)); reverseArray(intArray); println("Reverse: " + arrayToString(intArray)); } n 10 intArray ReverseArray Enter number of elements: 10 Forward: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Reverse: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] private int[] createIndexArray(int n) { int[] array = new int[n]; for ( int i = 0; i < n; i++ ) { array[i] = i; } return array; } 10 narrayi 012345678910 012345678 0000000000 9 0 9 1 8 2 7 3 6 4 5 5 4 6 3 7 2 8 1 9 0 private String arrayToString(int[] array) { String str = ""; for (int i = 0; i < array.length; i++) { if (i > 0) str += ", "; str += array[i]; } return "[" + str + "]"; } arrayistr 012345678910 00, 10, 1, 20, 1, 2, 30, 1, 2, 3, 40, 1, 2, 3, 4, 50, 1, 2, 3, 4, 5, 60, 1, 2, 3, 4, 5, 6, 70, 1, 2, 3, 4, 5, 6, 7, 80, 1, 2, 3, 4, 5, 6, 7, 8, 9 private void reverseArray(int[] array) { for (int i = 0; i < array.length / 2; i++) { swapElements(array, i, array.length - i - 1); } arrayi 012345 private void swapElements(int[] array, int p1, int p2) { int temp = array[p1]; array[p1] = array[p2]; array[p2] = temp; } array 9 p2 0 p1temp 0 public void run() { int n = readInt("Enter number of elements: "); int[] intArray = createIndexArray(n); println("Forward: " + arrayToString(intArray)); reverseArray(intArray); println("Reverse: " + arrayToString(intArray)); } nintArray 012345678 9876543210 9 0 10 26

Exercise Comp 101 | Özyeğin University27 Write the DiceRoll program using an array, instead of using a variable for each face value.

Comp 101 | Özyeğin University28 public class DiceRoll extends ConsoleProgram { private RandomGenerator rgen = RandomGenerator.getInstance(); private static final int NUM_ROLLS = 600000; public void run() { int[] faces = new int[6]; for(int i = 0; i < NUM_ROLLS; i++) { int n = rgen.nextInt(1, 6); faces[n-1]++; } for (int i = 0; i < faces.length; i++) { println("Percentage of " + (i+1) +"'s " + faces[i]*100.0/NUM_ROLLS + " %."); }

Arrays hold multiple values All values are of the same type Notation: [i] selects one array element [0] is always the first element Be careful with array bounds! Especially useful with large amounts of data Often processed within loops Entire array can be passed as an argument Summary

Extending an array Arrays are created with fixed length; they cannot be resized. Solution: Create a new array that is one element longer than the original. Copy each element from the original into the new array. Set the extra element of the new array. Assign the new array back to the original array variable.

Extending an array abcdef Create a new array that is one element longer than the original. originalArray newArray

Extending an array abcdef Copy each element from the original into the new array. originalArray newArray abcdef

Extending an array abcdef Set the extra element of the new array. originalArray newArray abcdefg

Extending an array abcdef Assign the new array back to the original array variable. originalArray newArray abcdefg

Download ppt "The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Arrays and ArrayLists C H A P T E R 1 1 1 slides partially adapted from."

Similar presentations