a rrays in j ava : t he b asics section 6.0 ap computer science
TRANSCRIPT
ARRAYS IN JAVA: THE BASICSSection 6.0
AP Computer Science
ARRAY STORAGE
Recall that arrays have two main parts: A name, which is used to reference the array An index value (also called subscript) that is
used to access specific values in the array.
grades
Array index values ALWAYS begin at zero!Largest index value in an array is size - 1
78 82 91 65 77
0 1 2 3 4
USING INDEX VALUES
To access individual values in an array, the name of the array is used with the index value inside of brackets. The brackets used with an array are treated as an operator with the highest precedence!
distance[10] = 27.25;speed = distance[i] / 5; System.out.println(“Distance = “ + distance[0]);
Because index values are integers, the value in the brackets MUST evaluate to an integer.
DECLARING ARRAYS
In Java, arrays are objects! Variables are object reference variables! Array must be instantiated!
Syntax of Array Declaration:type[ ] name = new type[size];
type = Data type for array name = Name of array size = # of items in the array
EXAMPLES OF ARRAY DECLARATIONS
int[] numbers = new int[10]; //10 slot array
int size = 20;double[] taxRates = new double[size]; //20 slots!
char [] colors;colors = new char[256]; //256 slot array
DECLARING ARRAYS
The data type for an array can be any primitive data type OR any object type (class).
All values stored in the array will have the same data type cannot mix and match!
Once the size of an array is declared, it cannot be changed.
BOUNDS CHECKING WITH ARRAYS
When an array location is accessed, the operator performs bounds checking making sure the provided index value is valid for the array. Index value MUST be in the range of 0 to (size – 1).
If the provided index value is invalid, Java will throw a ArrayIndexOutOfBoundsException.
Off-by-one Error Common error where the programmer “forgets” that each location is “off by one” (ex. the first location has an index of zero, NOT one)
OBTAINING THE LENGTH OF AN ARRAY
The length of an array can be quickly identified using the length constant available to all array objects. arrayName.length No parentheses!!!
The length constant is declared AFTER the array is instantiated.
INITIALIZER LISTS An initializer list is a list of values for an array that is
provided at the array’s initialization. The use of an initializer list is limited to when the array is declared.
To create an initializer list: Separate each item with a comma (,)
Each item MUST be of the same data type Enclose the list within braces Use the list in place of the new operator
The size of the array will become the # of items in the initializer list
Ex: int[] foodCost = {6.99, 7.25, 8.35, 6.50, 5.25};String[] names = {“Joe”, “Jack”, “Jane”, “Jenny”};
ARRAYS AND LOOPS
Due to the fixed size of an array, a for loop can be used to quickly work through and/or process the data contained in an array.
Specifically… Printing all of the values in an array Adding all of the values in an array Obtaining values for each “cell” in an array
EXAMPLE: OBTAINING VALUES
int[] nums = new int[10];Scanner scan = new Scanner(System.in);
for(int i = 0; i < nums.length; i++){
System.out.print(“Enter integer value: “);nums[i] = scan.nextInt();
}
EXAMPLE: FINDING THE TOTALdouble[] values = {13.45, 16.67, 18.91, 22.35, 4.51, 8.26};double total = 0;
for(int count = 0; count < values.length; count++){
total += values[count];}
System.out.println(“The total of all values is “ + total);
ARRAYS AND METHODS
Arrays can be used as parameters for class methods!
When writing a parameter list for a method, the parameter for the array will require the data type of the array, a set of brackets, and a parameter name. Ex: public int getTotal(int[] numbers)
Because an array is an object, any changes done to the array inside a method are PERMANENT!!!
ARRAYS OF OBJECTSSection 6.1
AP Computer Science
CREATING ARRAYS OF OBJECTS
Like primitive data types, arrays can be created that are filled with objects of a specific class.
Declaring an array of objects is identical to declaring an array of primitive data:
type [] arrayName = new type[size]; The data type, in this case, is the name of the
class being used.
EXAMPLE – CREATING OBJECT ARRAYS
String [] cityList = new String[10];//Creates an array of 10 String objects
Student[] classList = new Student[28];//Creates an array of 28 Student objects
Animal [] zoo;zoo = new Animal[30];//Creates an array of 30 Animal objects
WHY MAKE ARRAYS OF OBJECTS?
Can eliminate the need for parallel arrays (two or more arrays linked by their index values)
Useful for programs that contain a large number of similar objects. Example: Consider a program that manages a
roster of players for a football team.
ARRAYS OF OBJECTS & INSTANTIATION
An array of objects will hold a memory address in each slot. These memory addresses are the link to the stored objects.
Upon creation, each slot in the array is empty (null). Each object in the array MUST be instantiated by using a constructor method for each object.
SEARCHING ARRAYS
AP Computer Science
Section 6.2
HOW CAN SEARCH AN ARRAY FOR A VALUE?
2 4 7 11 14 15 23
LINEAR / SEQUENTIAL SEARCH
Algorithm Start at beginning of array Compare contents of first index to target
If value is found, stop loop Move to next index value. Repeat until value is
found.
Advantages Can be used with any array Easiest to implement
Disadvantage Very slow when working with large amounts of data
BINARY SEARCH
Algorithm: Pre-sort array from low to high / high to low Find middle of array and compare to target.
Consider only values in possible half of array Find middle of this “half” and compare to target
Continue in this manner until value is found/not found
Advantage Faster than Linear Search
Eliminate half of the possibilities each step of the way
Disadvantage Requires array to be sorted before the search.
BINARY SEARCH
2 4 7 11 14 15 23
2 4 7 11 14 15 23
2 4 7 11 14 15 23
Find 14… Start Here
Since 14 > 11, move to 2nd half
Since 14 < 15, move below
COMPARING VALUES
For primitive values (int, double, char, etc.), you can use normal equality and comparison operators.
For Strings… Use the .equals method to test for equality.
Returns true or false if(string1.equals(string2))
Use the .compareTo method to compare strings Returns 0 if equal, negative if s1 < s2, positive if s1 >
s2 if(string1.compareTo(string2) > 0)
WHEN TO USE EACH SEARCH METHOD
Use a linear search when… Amount of data to search is fairly small Data is not sorted Efficiency is not an issue
Use a binary search when… Amount of data to search is large Data is pre-sorted
SORTING ALGORITHMSSection 6.3
AP Computer Science
ESSENTIAL QUESTIONS
What is a selection sort?
What is a bubble sort?
What is an insertion sort?
SORTING
The process of rearranging the elements in an array in a specific order (lowest to highest or highest to lowest).
For now, we will learn about the… Selection Sort Bubble Sort Insertion Sort
SELECTION SORT A selection sort is sorting algorithm where,
one slot at a time, each value is placed in its proper location.
Starting at the first position in the array, the array is searched for the largest/smallest value. When it is found, the values are swapped.
At the next slot, the “rest” of the array is searched until the next largest/smallest value is found. These values are swapped.
This repeats until the end of the array.
SELECTION SORT - ALGORITHM
For each position in the array{
Find smallest/largest value from current position to end of the array.
Swap value in current position with found value.
}
SELECTION SORT
3 9 6 1 8 2 5
1 9 6 3 8 2 5
1 2 6 3 8 9 5
Start Here – Scan for smallest & swap
Scan from here
1 2 3 6 8 9 5
1 2 3 5 8 9 6
BUBBLE SORT
A bubble sort is a sorting method where adjacent values are compared and rearranged in the array until all are sorted.
This is called a “bubble” sort because the smaller values “float” to the top.
BUBBLE SORT - ALGORITHM
while #passes < size and numbers swapped{
increase #passes by 1for each index - #passes
compare two adjacent valuesif 2nd value greater than 1st, swap
}
BUBBLE SORT – PASS #1
3 6 1 8 2 5 9
3 9 6 1 8 2 5
3 9 6 1 8 2 5
3 6 9 1 8 2 5
3 6 1 9 8 2 5
3 6 1 8 9 2 5
3 6 1 8 2 9 5
BUBBLE SORT – PASS #2
3 1 6 2 5 8 9
3 6 1 8 2 5 9
3 6 1 8 2 5 9
3 1 6 8 2 5 9
3 1 6 8 2 5 9
3 1 6 2 8 5 9
3 1 6 2 5 8 9
BUBBLE SORT – PASS #3
1 3 2 5 6 8 9
3 1 6 2 5 8 9
1 3 6 2 5 8 9
1 3 6 2 5 8 9
1 3 2 6 5 8 9
1 3 2 5 6 8 9
1 3 2 5 6 8 9
INSERTION SORT
An insertion sort is similar to sorting a hand of cards.
In an insertion sort, each value is looked at and placed in its appropriate location in a “sorted” list.
INSERTION SORT - ALGORITHM
for each value in the array starting at 1{
Get value and index of current positionSearch “sorted” part of array for fitPlace value in new location
}
INSERTION SORT
1 2 3 6 8 9 5
1 2 3 6 8 5 9
3 9 6 1 8 2 5
3 9 6 1 8 2 5
3 9 6 1 8 2 5
3 6 9 1 8 2 5
1 3 6 9 8 2 5
1 3 6 8 9 2 5
COMPARING SORTSSection 6.4
EFFICIENCY Algorithm Efficiency – used to judge
algorithms based on speed and/or data.
Time Efficiency The time required for an algorithm to run completely.
Space Efficiency The amount of space (memory) an algorithm requires.
Using less space and/or completing in a faster time = more efficient algorithm
MEASURING EFFICIENCY
Time efficiency measured by how many statements get executed. More statements = larger time requirement
How does the running time grow as the size of the array grows?
SELECTION SORTfor(int i = 0; i < array.length; i++){
for(int s = i + 1; s < array.length; s++){//Statements inside}
}
If n is the number of items in the array, then the outer loop will run n times, while the inner loop will run from 1 – n times, depending on the outer loop.
Thus, its efficiency is n * n = n2
BIG – OH NOTATION
In Computer Science, big-oh notation is used to identify the time efficiency of an algorithm.
The selection sort has an efficiency of O(n2), which means that, as a worst case scenario, the algorithm will run on the order of n2 units of time.
INSERTION SORT
An insertion sort is ALSO a nested loop that run n times each, so the insertion sort also has an efficiency of O(n2).
BIG-O METHODS Common magnitudes of big-O notation are
(from least complex to most complex):
O(1) Constant O(log n) Logarithmic O(n) Linear O(n log n) n log n O(n2) Quadratic O(n3) Cubic O(2n) Exponential
O(1)
An O(1) algorithm is one which has a constant execution time, regardless of size.
Ex: public int sum(int[] a){
return a[0] + a[a.length – 1];}
O(N) An O(n) algorithm varies directly with the size of the
input data set. Single Loop Structure
Ex:public int search(int[] a, int searchVal){
for(int i = 0; i < a.length; i++)if(a[i] == searchVal)
return i;return -1;
}
ANOTHER O(N) EXAMPLE
int sum(int [] a, int i){
if (i > a.length)return 0;
elsereturn a[i] + sum(a, i+1);
}
O(N2) An O(n2) algorithm varies directly with the square of the size of the
data set. Common for programs with nested loops Additional nesting will result in O(n3), O(n4)
Ex: void bubbleSort(int[] a){
int k = 0; while(k < a.length() – 1){
k++;for(int j = 0; j < a.length() – k; j++)
if(a[j] < a[j + 1])swap(a, j, j+1);
}}
O(LOG N)
An O(log n) method will increase rapidly at the beginning, but will eventually level off in terms of a time requirement as the data set increases.
Ex: Binary Search Size of searched array continually is cut in half
HOW BIG-O VALUES VARY If n = 1
O(1) = 1 O(n) = 1 O(log n) = 0 O(n2) = 1
If n = 10 O(1) = 1 O(n) = 10 O(log n) = 1 O(n2) = 100
SPACE EFFICIENCY Space efficiency can also be measured using
big-oh notation.
In most sorting arrays, the amount of memory used is a number of memory locations equal to the array’s length.
Selection and Insertion sorts have efficiency levels of O(n).
WHAT DOES IT ALL MEAN?
Time efficiency is gained by limiting the number of lines of code the algorithm must process.
Sequential and Insertion Sorts have a time efficiency of O(n2) and a space efficiency of O(n).
Neither sort method has any real efficiency advantage over the other.
TWO – DIMENSIONAL ARRAYSSection 6.6
TWO DIMENSIONAL ARRAYS
Two Dimensional Arrays – an array that has values in “two – dimensions”. Typically imagined as “rows and columns”.
When using two-dimensional arrays, the reference requires two index values. The first index value is the “row” The second index value is the “column”
DECLARING TWO DIMENSIONAL ARRAYStype [] [] name = new type[#rows][#columns];
int [ ] [ ] values = new int [3][5]; Creates an array with 3 rows and 5 columns
double [ ] [ ] earnings = new double[5][5]; Creates an array with 5 rows and 5 columns
Monster [] [] house = new Monster[2][2]; Creates an array with 2 rows and 2 columns
INITIALIZING A 2D ARRAY
2D arrays can be initialized using an initializer list. However, each row must be contained in its own set of curly braces.
int[ ] [ ] ratings = { {5, 7, 8}, {2, 3, 4}}
This would be a 2 x 3 array 5 7 8 2 3 4
USING TWO-DIMENSIONAL ARRAYS
The index value of the first cell in the row AND column is zero.
To access/change the value of a cell, use the following: name[row][column] = value or expression;variable = name[row][column];
EXAMPLE
char[ ][ ] a = new char[3][4];
a[0][0] a[0][1] a[0][2] a[0][3]
a[1][0] a[1][1] a[1][2] a[1][3]
a[2][0] a[2][1] a[2][2] a[2][3]
EXAMPLE
char[ ][ ] a = new char[3][4];
‘a’ ‘b’ ‘c’ ‘d’
‘e’ ‘f’ ‘g’ ‘h’
‘i’ ‘j’ ‘k’ ‘L’
LENGTH OF TWO-DIMENSIONAL ARRAY
The length constant for a two dimensional array object CAN be used to quickly find the dimensions of the array, with the following considerations;
int [][] example = new int[5][3]; example.length Returns # of rows example[row].length Return # of columns
LOOPS AND TWO-DIMENSIONAL ARRAYS Two dimensional arrays can be manipulated
easily by using a nested for loop.
Typically, the outer for loop will keep track of the rows, while the inner loop will keep track of the columns.
for(int r = 0; r < array.length; r++)for(int c = 0; c < array[r].length; c++)
//Process elements
THE ARRAYLIST CLASSSection 6.7
THE ARRAYLIST CLASS
java.util.ArrayList
An arrayList object works just like a standard array. However…Does not need to be declared to store a
particular data type. (Stores list of references to the Object class)
Items can be added to or removed from the list at any point in time. This will cause the size to change.
This class is part of the Collections API
CREATING AN ARRAYLIST
To create an arrayList in a program, you need to…. import the appropriate library
import java.util.ArrayList; construct the arrayList
ArrayList variable = new ArrayList();
ARRAYLIST CLASS METHODS
boolean add (Object obj)Adds the object to the end of the ArrayList
void add (int index, Object obj)Adds the given object into the ArrayList at
the given position
Object set(int index, Object obj)Replaces the element at index with the
provided object, and returns the replaced object.
ARRAYLIST CLASS METHODS
Object get(int index) Returns the object at the given index.
Object remove(int index) Removes the object at the index from this list
and returns it.
int size() Returns the number of elements in the list
ARRAYLIST CLASS METHODS
void clear() Removes all elements from the list
boolean contains(Object obj) Returns true if the object is found in the list
int indexOf(Object obj) Returns the index of the first occurrence of the
object OR -1 if the object is not found.
WHAT CAN BE STORED IN ARRAYLISTS? ArrayLists can be used to store any object
An arrayList will store a list of references to the “Object” class (more on this later)
Primitive data can be stored in an arrayList by storing it in a Wrapper class.
WRAPPER CLASSES
A wrapper class is a class that is used to create an object that holds primitive data as an object. It “wraps” data into an object!
Wrapper classes exist for all primitive data types!
THE INTEGER WRAPPER CLASS
Integer(int value) Constructor creates new Integer object that
represents the value provided.
int compareTo(Object other) Returns a number indicating whether the integer
is less than (a negative return value), greater than (a positive return value), or equal (a zero return value) to the integer other.
THE INTEGER WRAPPER CLASS
boolean equals(Object other)Returns true if this integer has the same
value as the integer other.
int intValue()Returns the value of this object as an int.This “unwraps” the integer!
String toString()Returns a String object representing this
integer’s value.
EXAMPLE OF WRAPPING/UNWRAPPINGInteger num = new Integer(10);//num is now an Integer object that contains
the value 10.
int value = num.intValue();//value is now 10!
THE DOUBLE WRAPPER CLASS
Double(double value)
int compareTo(Object other)
double doubleValue()
boolean equals(Object other)
String toString()
The constructor and methods work in a similar way to the constructor and methods from the Integer class.
AUTOBOXING
Autoboxing is the automatic conversion between a primitive value and its appropriate wrapper object.
Integer numObject;int num1 = 22;numObject = num1; //Wraps
int num2 = numObject; //Unwraps
BACK TO ARRAYLISTS – ADDING/REMOVING Any time an object is added/removed
from an arrayList, the size changes automatically!!!
ArrayList class = new ArrayList();class.add(“Joe”); [“Joe”]class.add(“Megan”); [“Joe”, “Megan”]class.add(“Carol”); [“Joe”, “Megan”, “Carol”]class.remove(“Joe”); [“Megan”, “Carol”]
ARRAY LISTS OF OBJECTS
Because an arrayList holds references to the base Object type, it can contain any object.
To receive a specific object from an arrayList, the returned object needs to either…Be cast as the objectBe obtained from an arrayList that has a
specified type.
OPTION 1: CASTING OBJECTS You can cast objects as specific types in a
similar way to casting data as primitive types.
Ex: (className)variable Ex: (className)variable.method()
t = (Toy)aList.get(0);
OPTION 2: SPECIFY TYPE OF LIST
An arrayList can be created to hold objects of a specific type.
ArrayList <className> variable = new ArrayList <className>();
Ex: ArrayList<Student> sList = new ArrayList<Student>();
ARRAYLISTS AND EFFICIENCY
When items are added/removed from the end of an ArrayList, efficiency is NOT affected. Don’t need to waste time/space moving
items around.
When items are added/removed from the front of a long ArrayList, efficiency decreases due to the need to copy/move items.
EXAMPLE: SHUFFLED DECK
Use the Card class to create a deck of cards in an ArrayList.
“Shuffle” the deck and print the cards out one at a time, including the number left in the deck.