cse 1223 introduction to computer programming in...
TRANSCRIPT
1
CSE 1223: Introduction to Computer Programming in Java
Chapter 6 – Arrays
A New Problem
Consider the following task: Input N real numbers representing temperature
measurements and compute the following: the average, minimum, and maximum temperature the number of temperatures that are above the average
and the number of temperatures that are below the average
the median temperature
2
What’s the Problem?
We need to store all the temperatures beforewe can perform some of the computation
How many variables do we need? What are we going to name them?
3
The Solution: Arrays
An array is a sequence of variables of the same data type (any type can be used: e.g., int, double, boolean, String, etc.)
Each variable in the array is called an element
Array elements are accessed through an index (their position in the array)
4
An Example
int N = 5;
double [] temperatures;
temperatures = new double[N];
Scanner in = new Scanner(System.in);
int pos = 0;
while (pos < N)
{
temperatures[pos] = in.nextDouble();
pos = pos + 1;
}
5
An Example
int N = 5;
double [] temperatures;
temperatures = new double[N];
Scanner in = new Scanner(System.in);
int pos = 0;
while (pos < N)
{
temperatures[pos] = in.nextDouble();
pos = pos + 1;
}
6
declare an array variablecalled temperatures whoseelements will be double variables
An Example
int N = 5;
double [] temperatures;
temperatures = new double[N];
Scanner in = new Scanner(System.in);
int pos = 0;
while (pos < N)
{
temperatures[pos] = in.nextDouble();
pos = pos + 1;
}
7
declare an array variablecalled temperatures whoseelements will be double variables
create an actual array withN=5 elements of type double
An Example
int N = 5;
double [] temperatures;
temperatures = new double[N];
Scanner in = new Scanner(System.in);
int pos = 0;
while (pos < N)
{
temperatures[pos] = in.nextDouble();
pos = pos + 1;
}
8
access the element at position posin array temperatures
declare an array variablecalled temperatures whoseelements will be double variables
create an actual array withN=5 elements of type double
Declaring Arrays
Arrays are declared like normal variables with the addition of [ ] between type and name, e.g.
double [] temperatures;
int [] scores;
boolean [] answers;
String [] names;
The declaration does not specify the number of elements
Declaring an array does not reserve (allocate) memory for the array elements
9
Allocating The Array
To allocate memory space for the array elements we need to use the new operator, e.g.,
temperatures = new double[10];int numScores = 8;scores = new int[numScores];answers = new boolean[4];names = new String[5];
new is followed by the type of the elements and the number of elements between [ ]
The number of elements can be any expression that evaluates to a positive integer value
10
Accessing Array Elements
Elements of an array are accessed by using the name of the array variable followed by the index (position in the array) of the element between [ ], e.g.,
temperatures[2]
scores[numScores-1]
answers[0]
names[3]
The index can range between 0 and the number of elements in the array - 1
11
Array Length
Once we declare and allocate an array, we can retrieve the array length (the number of elements in the array) from a variable called arrayName.length, e.g.,
temperatures.length is 10scores.length is 8answers.length is 4names.length is 5
12
Your Turn
Declare and allocate an array of 10 integers, call it a
13
Your Turn cont.
Write a loop that initializes the 10 elements of the array to the integers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
14
Your Turn cont.
Write a loop that outputs the elements of the array, one per line
15
Your Turn cont.
Write a loop that outputs the elements of the array, one per line, in reverse order
16
Your Turn cont.
Write a piece of code that checks if the elements in an array of char form a palindrome
17
For Loops
A different syntax for a familiar concept They work well with arrays
18
for (init; test; update){
for_block}
For Loops
A different syntax for a familiar concept They work well with arrays
19
for (init; test; update){
for_block}
initwhile (test){
for_blockupdate
}
For Loops
A different syntax for a familiar concept They work well with arrays
20
for (init; test; update){
for_block}
initwhile (test){
for_blockupdate
}
boolean expression
statement sequence
statements
For Loops
A different syntax for a familiar concept They work well with arrays
21
for (init; test; update){
for_block}
initwhile (test){
for_blockupdate
}
boolean expression
statement sequence
statements
Example
Rewrite the loop that initializes the 10 elements of an array to the integers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
int i = 0;while (i < 10){
a[i] = i + 1;i++;
}
22
Example
Rewrite the loop that initializes the 10 elements of an array to the integers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
int i = 0;while (i < 10){
a[i] = i + 1;i++;
}
23
for (int i = 0; i < 10; i++)
{
a[i] = i + 1;
}
Your Turn (Our Old Friend)
Write a for loop that given a String variable str and a character variable ch, counts and outputs the number of occurrences of character ch in String str.
24
Your Turn, Again
Write a program segment—using for loops—that given two integer variables, width and height, outputs a rectangle of ‘+’s of the given width and height.
25
Arrays And Methods
Arrays can be passed as parameters to methods and can be returned by methods (functions), e.g.,
private static void printArray(double[] a) private static void clearArray(int[] a) private static int[] copyArray(int[] a) private static int indexOfSmallest(
int startIndex, double[] t) private static void sort(double[] temps)
26
Print an array
public static void print(int[] arr)
Given the above method header, write a method that prints each element of arr on a separate line (in order).
27
Contains
public static boolean contains(int[] arr, int val)
Given the above method header, write a method that returns true if val is one of the elements in the array arr, false otherwise.
28
Copy
public static int[] copy(int[] arr)
Given the above method header, write a method that returns a new array which is a copy of the given one (same length, same elements)
29
Arrays as Reference Types
Arrays in Java are objects Array variables hold a reference to an array object Arrays have a reference type rather than a
primitive type Variables with a reference type hold a reference to a
memory location of an object of that type The value of the variable is just the memory address where
the object is stored in memory This leads to some non-intuitive behavior for variables with
reference types, including arrays
30
Reference types vs. Primitive Types
What do you expect this segment of code to do?int i = 12;
int j = i;
j = j + 1;
System.out.println(i);
System.out.println(j);
31
Reference types vs. Primitive Types
What do you expect this segment of code to do?int i = 12;
int j = i;
j = j + 1;
System.out.println(i);
// reports 12
System.out.println(j);
// reports 13
32
Reference types Now what do you expect this segment of code
to do?int[] a1 = new int[2];
a1[0] = 2;
int[] a2 = a1;
a2[0] = 6;
System.out.println(a1[0]);
System.out.println(a2[0]);
33
Reference types Now what do you expect this segment of code
to do?int[] a1 = new int[2];
a1[0] = 2;
int[] a2 = a1;
a2[0] = 6;
System.out.println(a1[0]);
// reports 6
System.out.println(a2[0]);
// reports 6
34
Reference types Why the “strange” behavior on the array
example? Because arrays are reference typesint j = i;
The above copies the value stored in i into the variable jint[] a2 = a1;
This line does NOT make a copy of the object a1 into the object a2 This line instead copies the memory location stored in the variable a1
into the variable a2 Both of these variables now reference (or “point to”) the same memory
location We call this aliasing or making an alias. Both a1 and a2 are now two
different names for the same object.
35
Reference Types
36
a1:
[ 0, 0 ]
int[] a1 = new int[2]
New array of length 2 created.Reference a1 assigned to referto it.
Note that this triangleis what we’ll use to denote areference type.
Reference Types
37
a1:
[ 2, 0 ]
int[] a1 = new int[2]a1[0] = 2
Assign the value of 2 to position0 of the array
Reference Types
38
a1:
[ 6, 0 ]
int[] a1 = new int[2];a1[0] = 2;int[] a2 = a1;a2[0] = 6;
The values at position 0 isoverwritten to become 6. Notethat since this happens to the object,it is reflected when either a1[0] ora2[0] is accessed.
a2:
Reference Types Upshot: Be careful when dealing with
reference types Variables hold memory locations – programs may
not run as intended Example: equality tests (==)
If a1 and a2 are both of type ArrayList, what is this boolean test really doing?
(a1 == a2)
What if a1 and a2 were of type String? This is why we can’t use == to test for String equality in our
programs! Strings are a reference type. We need to use .equals() for Strings
39
Arrays and Methods Reference types also behave somewhat
differently when passed as parameters to methods When we pass a primitive type we are passing a
copy of the value that primitive type holds to the method
When we pass a reference type we are passing a copy of a reference to the method This means that changes to an object through a
reference will “stick” when the method is finished –unlike changes to a variable of a primitive type.
40
Clear an array
public static void clear(int[] arr)
Given the above method header, write a method that sets each element of arr to 0.
41
Array Methods Java ships with a number of different
methods for manipulating arrays Built into the standard library In the “java.util.Arrays” package To use, put:
import java.util.Arrays
at the top of your code.
When manipulating arrays it is best practice to re-use the methods in the Arrays library
http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html
42
Arrays.equals
static boolean Arrays.equals(int[] a, int[] a2)
Returns true if a and a2 are the same length and have the same elements in the same order Use this in boolean expressions instead of ‘==‘
if (Arrays.equals(a1,a2){System.out.println(“They are equal!”);
}else {System.out.println(“not equal!”);
}
43
Arrays.copyOf
static int[] Arrays.copyOf(int[] a, int newLength)
Returns a new array of length newLength containing a copy of the first newLength elements of the array a If a is shorter then newLength, the extra positions are padded
with zeroes
int[] arr = {1,2,3};int[] copy = Arrays.copyOf(arr,arr.length);
// copy now holds copies of the same elements as// arr
44
Arrays.fill
static void Arrays.fill(int[] a, int value)
Sets every element of the array referred to by the reference a with the value value Use this to reset the values in an array back to zero or another
default value
int[] arr = {1,2,3};Arrays.fill(arr, 0);
// arr is now the array {0,0,0}
45
Arrays.sort
static void Arrays.sort(int[] a)
Sorts the array a in ascending order in place
int[] arr = {10,2,50};Arrays.sort(arr);
// arr is now the array {2,10,50}
46