cse 1223 introduction to computer programming in...

46
1 CSE 1223: Introduction to Computer Programming in Java Chapter 6 – Arrays

Upload: doankien

Post on 17-Feb-2019

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

1

CSE 1223: Introduction to Computer Programming in Java

Chapter 6 – Arrays

Page 2: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 3: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 4: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 5: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 6: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 7: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 8: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 9: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 10: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 11: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 12: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 13: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

Your Turn

Declare and allocate an array of 10 integers, call it a

13

Page 14: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 15: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

Your Turn cont.

Write a loop that outputs the elements of the array, one per line

15

Page 16: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

Your Turn cont.

Write a loop that outputs the elements of the array, one per line, in reverse order

16

Page 17: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

Your Turn cont.

Write a piece of code that checks if the elements in an array of char form a palindrome

17

Page 18: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

For Loops

A different syntax for a familiar concept They work well with arrays

18

for (init; test; update){

for_block}

Page 19: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

}

Page 20: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 21: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 22: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 23: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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;

}

Page 24: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 25: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 26: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 27: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 28: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 29: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 30: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 31: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 32: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 33: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 34: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 35: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 36: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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.

Page 37: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

Reference Types

37

a1:

[ 2, 0 ]

int[] a1 = new int[2]a1[0] = 2

Assign the value of 2 to position0 of the array

Page 38: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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:

Page 39: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 40: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 41: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 42: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 43: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 44: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 45: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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

Page 46: CSE 1223 Introduction to Computer Programming in Javaweb.cse.ohio-state.edu/cse1223/slides/06Arrays.pdf · The Solution: Arrays An . array. is a sequence of variables of the same

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