The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Arrays and...
-
Upload
larry-orman -
Category
Documents
-
view
227 -
download
1
Transcript of The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Arrays and...
The Art and Science of
An Introductionto Computer ScienceERIC 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 University 2
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
Recap: Arrays
3
int score = 0;int[] scores = new int[10];
0 1 2 3 4 5 6 7 8
0 0 0 0 0 0 0 0 0 09
scores
0score
Element type
Length
index
Acessing Arrays
0 1 2 3 4 5 6 7 8
0 0 0 0 0 0 0 0 0 09
scores
int[] scores = new int[10];
0 1 2 3 4 5 6 7 8
25 0 0 0 0 0 0 0 0 09
scores
scores[0] = 25;
0 1 2 3 4 5 6 7 8
25 17 0 0 0 0 0 0 0 09
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 University 6
• 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 University 7
• 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 University 8
• 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 University 9
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];
0score
0 1 2 3 4 5 6 7 8
0 0 0 0 0 0 0 0 0 09
scores
11
Internal Representation of Arraysint score = 5;int foo = score;foo++;println(score); // prints 5println(foo); // prints 6
5score foo
12
Internal Representation of Arraysint score = 5;int foo = score;foo++;println(score); // prints 5println(foo); // prints 6
5score
5foo
13
Internal Representation of Arraysint score = 5;int foo = score;foo++;println(score); // prints 5println(foo); // prints 6
5score
6foo
14
Internal Representation of Arraysint score = 5;int foo = score;foo++;println(score); // prints 5println(foo); // prints 6
5score
6foo
15
Internal Representation of Arraysint[] scores = new int[10];int[] numbers = scores;numbers[5] = 42;println(scores[5]); // prints 42println(numbers[5]); // prints 42scores[0] = 77;println(scores[0]); // prints 77println(numbers[0]); // prints 77
0 1 2 3 4 5 6 7 8
0 0 0 0 0 0 0 0 0 09
scores
numbers
16
Internal Representation of Arrays
0 1 2 3 4 5 6 7 8
0 0 0 0 0 0 0 0 0 09
scores
numbers
int[] scores = new int[10];int[] numbers = scores;numbers[5] = 42;println(scores[5]); // prints 42println(numbers[5]); // prints 42scores[0] = 77;println(scores[0]); // prints 77println(numbers[0]); // prints 77
17
Internal Representation of Arrays
0 1 2 3 4 5 6 7 8
0 0 0 0 0 42 0 0 0 09
scores
numbers
int[] scores = new int[10];int[] numbers = scores;numbers[5] = 42;println(scores[5]); // prints 42println(numbers[5]); // prints 42scores[0] = 77;println(scores[0]); // prints 77println(numbers[0]); // prints 77
18
Internal Representation of Arrays
0 1 2 3 4 5 6 7 8
0 0 0 0 0 42 0 0 0 09
scores
numbers
int[] scores = new int[10];int[] numbers = scores;numbers[5] = 42;println(scores[5]); // prints 42println(numbers[5]); // prints 42scores[0] = 77;println(scores[0]); // prints 77println(numbers[0]); // prints 77
19
Internal Representation of Arrays
0 1 2 3 4 5 6 7 8
77 0 0 0 0 42 0 0 0 09
scores
numbers
int[] scores = new int[10];int[] numbers = scores;numbers[5] = 42;println(scores[5]); // prints 42println(numbers[5]); // prints 42scores[0] = 77;println(scores[0]); // prints 77println(numbers[0]); // prints 77
20
Internal Representation of Arrays
0 1 2 3 4 5 6 7 8
77 0 0 0 0 42 0 0 0 09
scores
numbers
int[] scores = new int[10];int[] numbers = scores;numbers[5] = 42;println(scores[5]); // prints 42println(numbers[5]); // prints 42scores[0] = 77;println(scores[0]); // prints 77println(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 100, 101, 102, 103, and 104:
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 University 25
• 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: 10Forward: [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
n arrayi
012345678910
0 1 2 3 4 5 6 7 8
0 0 0 0 0 0 0 0 0 09
09 18 27 36 45 54 63 72 81 90
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
01234567891000, 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));} n intArray
0 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 09
0
10
26
Exercise
Comp 101 | Özyeğin University 27
• Write the DiceRoll program using an array, instead of using a variable for each face value.
Comp 101 | Özyeğin University 28
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
a b c d e f
• Create a new array that is one element longer than the original.
originalArray
newArray
Extending an array
a b c d e f
• Copy each element from the original into the new array.
originalArray
newArray
a b c d e f
Extending an array
a b c d e f
• Set the extra element of the new array.
originalArray
newArray
a b c d e f g