arrays an array is a data structure that consists of an ordered collection of similar items (where...
TRANSCRIPT
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.
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
Array Manipulations
declare and instantiate the arrayint[] a; // declare arrayint [] a = new int[5]; // instantiate array of size 5.At this point, the array exists, and is initialized as follows:
[ 0 0 0 0 0 ]
Student[] s = new Student[5]; // declare and instantiate an array.At this point, the array exists, and is initialized as follows:[ null null null null null ]
Option two: explicitly define initial values (mildly helpful):int[] b = { 1, 2, 3, 4, 5 };[1 2 3 4 5]
<array name>[<index>]a. Index must be between 0 and the length minus b. The subscript operator ([ ]) has the same precedence as the method selector (.).c. The JVM checks the values of subscripts before using them.
a. Throws an exception if they are out of bounds (less than 0 or greater than array length minus 1).b. The detection of a range-bound error is similar to the JVM’s behavior when a program attempts to divide by
0.c. array length is stored in the public instance variable length.
practice
• Make arrays for a few minutes….1. Declare and instantiate an array of 10
integersInt[] 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
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 programtest[i + 1] = 115; // this is position 5..fill in the other elements….
Last item will be test[9] = < value> //why?
Manipulating an arrayFor an array where….test[3] = 50;test[5] = 110;int i = 3;int x;
x = test[5]; // x now equals 110test[5] = test[ 3]; // test[5] now equals 50test[i] = x; // test[3] now equals 110What did we do???
Declare and instantiate an array of ints. Then write code to swap the first two elements
Common activity: looping through an arrayTraversal: a loop that iterates through an array one element at a time.
Example: count the occurrence…
• Other examples of what you can do with loops and arrays…1. Sum the elements2. Determine presence of absence of a number3. Determine first location
• To work with arrays of any size, use the length instance variable in the loop.
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
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”);ElseSystem.out.println(“not found”);
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”);elseSystem.out.println(“found “ + x + “ at “ + location);
Find max of an array
Count number of occurrences of a given int
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)
Let’s look at declaring arrays in detail
Declaring an array:• Example: array of integers
Arrays are objects and must be instantiated before using.
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.
• 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.
We’ve seen this before
• 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.
Show examples of arrays of other types:
• double• boolean• String• Student
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.
• 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
For example:
• Int[] = {1,2,3,4,5,0,0,0,0,0 };• int nextFree = 5;• int[nextFree] = 6;• nextFree++;• Int[nextFree] = 7; nextFree++;• Etc. • // current state: {1,2,3,4,5,6,7,0,0,0 }
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?
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?
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);
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.
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.
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.
• A method can instantiate a new object or array and return it using the return statement.
methods
• Sum of elements• Search for a value• Sum of a row or rows in 2D array• Copy arrays
copy arrays
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.
Some reminders and tips
1. 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.
2. Try to estimate the number of cells needed for an array when creating it.
3. Array variables are null until assigned objects.4. The index of an array cell ranges from 0 to the
length of the array minus 1.5. To access the last cell, use
<array>.length-1.6. Avoid having more than one array variable refer
to the same array object.7. When an array is not full, track the current
number of elements.
Case Study –Student test scores
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.
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).
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".
Interlude: find the smallest distance between two
neighboring numbers in an array
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.