Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.

Similar presentations


Presentation on theme: "Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array."— Presentation transcript:

1 Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array is bound to a variable. We’ll refer to the array using the name of that variable. The items in an array are referred to in terms of their position (index or subscript) in the array. Arrays are used to store and manipulate multiple values.

2 Key concepts to develop
Items in the array are called elements. All elements are same type. type can be any primitive or reference type. Including, of course, classes you define length of an array = the number of elements. The first element is element[0], the second is element[1], etc. item’s position is its index or subscript. An array with n elements is indexed from 0 to n-1, inclusive

3

4 Array Manipulations declare and instantiate the array
int[] a; // declare array int [] a = new int[5]; // instantiate array of size 5. At this point, the array exists, and is initialized as follows: [ ] Student[] s = new Student[5]; // declare and instantiate an array. [ null null null null null ] Option two: explicitly define initial values (mildly helpful): int[] b = { 1, 2, 3, 4, 5 }; [ ] <array name>[<index>] Index must be between 0 and the length minus The subscript operator ([ ]) has the same precedence as the method selector (.). The JVM checks the values of subscripts before using them. Throws an exception if they are out of bounds (less than 0 or greater than array length minus 1). The detection of a range-bound error is similar to the JVM’s behavior when a program attempts to divide by 0. array length is stored in the public instance variable length.

5 practice Make arrays for a few minutes….
Declare and instantiate an array of 10 integers Int[] test = new int[10]; If we want to look at any element for this array: test[<index>] -like strings: count of index begins at 0 -last index is length - 1

6 To assign numbers to this array
test[0] = 20; test[1]= 35; test[2] = 50; test[3]= (test[1] + test[2]); test[i] = 100; // i was declared at 4 earlier in the program test[i + 1] = 115; // this is position 5 ..fill in the other elements…. Last item will be test[9] = < value> //why?

7 Manipulating an array For an array where…. test[3] = 50; test[5] = 110; int i = 3; int x; x = test[5]; // x now equals 110 test[5] = test[ 3]; // test[5] now equals 50 test[i] = x; // test[3] now equals 110 What did we do???

8 Declare and instantiate an array of ints
Declare and instantiate an array of ints. Then write code to swap the first two elements

9 Common activity: looping through an array
Traversal: a loop that iterates through an array one element at a time. Example: count the occurrence…

10 Other examples of what you can do with loops and arrays…
Sum the elements Determine presence of absence of a number Determine first location To work with arrays of any size, use the length instance variable in the loop.

11 Example 1: sum 1. Example: Sum the elements: adds the elements at each index to sum… int sum; sum = 0; For (int i =0; i< <arraylength>; i++) sum+= <arrayname>[i]; // subscript or index of array

12 Example 2: Determine presence of a number
int x; Boolean numfound; x = <what you are looking for>; numfound = false; for (int i=0; i< <arraylength>; i++) { if (<arrayname>[i] ==x) numfound= true; break; } if (numfound) System.out.println(“found it”); Else System.out.println(“not found”);

13 Example 3: Determine first location
int x; int location; x= <number you are looking for>; location = -1; // indicates you haven’t found it yet for (int i; i < <length>; i++) { if (<array>[i] == x) location = i; break; } if (location == -1) System.out.println(“not found”); else System.out.println(“found “ + x + “ at “ + location);

14 Find max of an array

15 Count number of occurrences of a given int

16 Find mode (project 10-3) Declare and instantiate an array of length 100. Populate the array with random numbers 0-9 Use the random class Using a for loop, iterate through the array and determine the mode (most common number)

17 Let’s look at declaring arrays in detail
Declaring an array: Example: array of integers

18 Arrays are objects and must be instantiated before using.

19 Arrays are objects….. This should sound a bit familiar
Array variables are null before they are assigned array objects. Failure to assign an array object can result in a null pointer exception In practice, this means that initializing an array of objects is a two step process. Step 1: initialize the array itself Student s[] = new Student[100]; -Step 2: initialize the object at each index for (int i = 0; i < s.length; i++) s[i] = new Student(); If you skip step 2, s[1].getScore() will throw a null pointer exception.

20 Two variables can refer to the same array.
double[] d = new double[4]; double[] e = d; To have two variables refer to two separate arrays that have the same values, copy all of the elements from one array to the other. Because arrays are objects, Java’s garbage collector sweeps them away when they are no longer referenced.

21 We’ve seen this before

22 Arrays can be declared, instantiated and initialized in one step.
The list of numbers between the braces is called an initializer list. Int[] abc = {1,2,3,4,5}; //abc now ref an array of five integers. Arrays can be formed from any collections of similar items. booleans, doubles, characters, Strings, and students. Once an array is instantiated, its size cannot be changed.

23 Show examples of arrays of other types:
double boolean String Student

24 The array does not need to be ‘full’ at any given time
When an array is instantiated, the computer fills its cells with default values. Then the application replaces the values with new ones as needed. An application might not use all of the cells available in an array. Physical size: the number of cells in an array. Logical size: the number of cells being used.

25 Using variable to track logical size in an array that is not full
Processing elements in array that is not full Adding elements to an array Removing elements from an array Text files and input from keyboard

26 For example: Int[] = {1,2,3,4,5,0,0,0,0,0 }; int nextFree = 5;
Int[nextFree] = 7; nextFree++; Etc. // current state: {1,2,3,4,5,6,7,0,0,0 }

27 Interlude: Stack Define a data type, Stack.java,
Our state defined by an array of ints of length 100, and a pointer into the array that tracks its logical size Behavior is defined by three methods The method declarations are: public void push(<int>) // adds an int to the array -public int peak() // return the last int added and keep it in array public int pop() // return the last int added and remove it from array Why is this a useful data type?

28 Parallel Arrays Just a way of associating different types of information. For example, consider having one array of students and a parallel array of ages. Then, e.g., if Sue is the first student: studentArray[0].getName() is “Sue” ageArray[0] is Sue’s age. What’s another way to achieve this behavior?

29 Enhanced for loops for arrays
for( int i = 0; i < x.length; i++) System.out.println(x[i]); is the same as… for(int i : x ) System.out.println(i);

30 Some rules for using enhanced for loop
A break statement can be used to terminate early. The enhanced for loop cannot be used to: Iterate through an array backwards Assign elements to positions in an array. Track the index position of the current element. Access any element other than the current element on each pass. shouldn’t be used for an array that’s not filled.

31 Using Arrays They are objects so some reminders about objects in general: When an object is used as a parameter to a method, what actually gets passed is a reference to the object. Not the object itself. The actual and formal parameters refer to the same object. Changes made to the object’s state are in effect after the method terminates.

32 So…… Arrays are objects, so the same rules apply. When an array is passed as a parameter to a method, the method manipulates the array itself. Changes made to the array in the method are in effect after the method is executed. Passing an array to a method leads to trouble if the method mishandles the array.

33 A method can instantiate a new object or array and return it using the return statement.

34 methods Sum of elements Search for a value
Sum of a row or rows in 2D array Copy arrays

35 copy arrays

36 Arrays of Objects – going back to our student class
Arrays can hold references to objects of any type. When an array of objects is instantiated, each cell is null by default until reset to a new object.

37 Some reminders and tips
To set up an array: Declare an array variable. Instantiate an array object and assign it to the array variable. Initialize the cells in the array with data, as appropriate. Try to estimate the number of cells needed for an array when creating it.

38 Array variables are null until assigned objects.
The index of an array cell ranges from 0 to the length of the array minus 1. To access the last cell, use <array>.length-1. Avoid having more than one array variable refer to the same array object. When an array is not full, track the current number of elements.

39 Case Study –Student test scores

40 interlude Read 10 ints from System.in, and store them in an array. For each int in the array, display a line with that many ‘*’ characters.

41 interlude Read in 10 ints from the keyboard, and store them in an array. Find the position (or index) of the maximum and minimum values in the array, and swap them (move the biggest element to the position of the smallest, and move the smallest element to the position of the biggest).

42 interlude . Read 10 ints from the keyboard, and store them in an array. Display "true" on the screen if there is an even number of even numbers among these 10. Otherwise, display "false".

43 Interlude: find the smallest distance between two neighboring numbers in an array

44 Inderlude: hard Longest Plateau:
Given an array of integers, find the length and location of the longest contiguous sequence of equal values wherethe values of the elements just before and just after this sequence are smaller.


Download ppt "Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array."

Similar presentations


Ads by Google