Unit 6 Note Packet Key
Unit 6 Note Packet Key
What is an Array?
An array is a special type of object than can hold a fixed number of items of the same data type.
Why? It leads to simpler code.
If we have a lot of data of the same type, we would need to create lots of individual variables to hold that data.
For example, let’s say you had a list of 4 songs:
1
Array Creation
Arrays can be created two ways: when you know the contents at creation and when you do not know the contents.
If you know the contents of the array when you are ready to create it, you use the following syntax:
o Type[] name = {<content>, <content>, <content>, …};
Each array element is separated with a comma and is the same data type
You CANNOT mix data types in an array
In our example, we would create an array with those four songs as:
o String[] songs = {“Our Song”, “Shake It Off”, “All Too Well”, “Red”};
If you do not know the contents of the array, you can use the following syntax to create it:
o Type[] name = new Type[length];
Notice that the new operator is used and in the second set of square brackets, you would put the length of the array you want.
In our example, we would create an array with a length of four as:
o String[] songs = new String[4];
int[] numbers = new int[10] boolean[] flags = {true, false, true}; double[] grades = new double[50];
//this is an error
int[] grades = new int[5];
grades = {89, 99, 85, 82, 93};
Instead, we use the array index to access and modify an array’s contents after it has been created:
We can manipulate array elements using any operators as well. What are the contents of grades after the code has executed?
To access the length of the array, you will use an attribute called length to retrieve the length of the calling array.
This is called an attribute and not a method because it is a built-in property and it not calling on a method.
Therefore, unlike the stringName.length(), the arrayName.length does not use any parentheses.
3
System.out.println(grades[grades.length]);
System.out.println(grades[-3]);
System.out.println(grades[1.5]);
Traversing an Array
To traverse the contents of an array, we use a for loop to access each item in the array.
The variable used in the for loop header is the index, and is usually called i
Inside the for loop, we can either access or modify the contents of the array using the index
Practice
1) What is printed? 2) What is printed?
int[] values = {2, 7, 11, 4, 13, 8}; int[] values = {2, 7, 11, 4, 13, 8};
for(int i = 0; i < values.length; i++) for(int i = 0; i < values.length; i++)
{ {
if(values[i] % 2 == 0) if(i % 2 == 0)
System.out.print(values[i] + “ “); System.out.print(values[i] + “ “);
} }
The even elements in the array: 2 4 8 The elements of the even indexes: 2 11 13
The words that have a word length larger than 4: horse chicken sheep Starting at the last index, if the word’s second letter is an “o”, print it off:
goat cow horse
5) Finish the code so that the sum of the elements in the array is printed. 6) Finish the code so the sum of the odd elements in the array is printed.
int[] arr = …; //array elements are not shown int[] arr = …; //array elements are not shown
int sum = 0; int sum = 0;
6
Methods can also return arrays. What is printed when the following code is run?
otherArr gets assigned to newArr, therefore
public class ExampleTwo { otherArr = [false, true, false,
public static void main(String[] args) { true, false]
numbers never changed, so when we go through both
int[] numbers = {-10, 15, -20, 25, -30}; arrays
boolean[] otherArr = positives(numbers);
for(int i = 0; i < numbers.length; i++){ Console:
-10 false
System.out.println(numbers[i] + " " + otherArr[i]); 15 true
} -20 false
25 true
} -30 false
Searching an Array
Searching an array is doing exactly what it sounds like: we search an array for an element Binary search is discussed in
In a linear search algorithm, we search an array for a specific algorithm by doing the following: Unit 7 & 10 and the sorting
algorithms will be discussed in
o starting at index 0, go up through the array one element at a time Unit 7 (selection and insertion) &
o check to see if the current index contains the element you are looking for 10 (merge sort)
Below are the steps for the linear search algorithm. In the space to the right, write the algorithm as a static method.
Practice
8
/** Returns the last index of a value
* Precondition: passed a non-empty array of integers and a value to find
*/
Common Algorithms
When we have an array of data, there are some common tasks we end up performing on it
The algorithms we will create on the next few pages are a snapshot of those common tasks
These algorithms happen so frequently, you will want to make sure you understand how they accomplish their task
Do you have to memorize them? No. BUT you’ll use them so often it is helpful to know the best way to accomplish these tasks
Write a method called max /** Returns the index of the largest number
9
* Precondition: passed a non-empty array of integers
*/
10
/** Returns true if there is at least one negative in an array of ints
* Precondition: passed a non-empty array of integers
*/
11
/** Returns the number of elements that are divisible by 3
* Precondition: passed a non-empty array of integers
*/
Swapping Algorithm
To swap two elements of the array, a simple algorithm can be followed:
1. Store the value of the first element in a temporary variable
2. Assign the value of the second element to the first element
3. Assign the value of the temporary variable to the second element
12
/** Shifts all the elements of an array to the left
* Precondition: passed a non-empty array of integers
*/
When reading this code, we say “for each var in array, do this with var”
For each iteration of the loop, the variable var will reference the current element in the array. When the loop repeats, the variable var will reference the
next element in the array, and so on.
Printing the contents of an array with a for loop Printing the contents of an array with an enhanced for loop
14
In an array of integers called numList, print off the odd elements. In an array of Strings called words, print off the first letter of each word.
While any for-each loop can be written as a for loop, the opposite is not true.
There are some limitations when it comes to a for-each loop in an array
For example, you cannot modify the contents of an array in a for-each loop:
While the code below is correct and will run, the variable num is a local
variable to the loop, and gets assigned the value of the element in the list. To modify the contents of the array, you would need to use a for loop
The list does not get modified, just the variable num does.
int[] arr = {2, 5, 3, 7, 9}; int[] arr = {2, 5, 3, 7, 9};
The for-each loop also has many limitations when it comes to ArrayLists, which will be discussed in Unit 7.
Lesson 5: Arrays of Objects
Objectives
15
VAR-2.A: Represent collections of related primitive or object reference data using one-dimensional (1D) array objects
Arrays of Objects
An array can hold any data type, including objects!
When visualizing an array of objects, lets think back to our Dog class from earlier units.
doggieList
This creates an array of 4 Dog references. Right now, however, the Dog objects have not been created so each value has a null reference in it.
To create the Dog, we will still have to call on a constructor, and we need to do this for each Dog element in the array:
doggieList
doggieList[0] = new Dog();
doggieList[1] = new Dog(“Fido”, 3, true);
doggieList[2] = new Dog(“Bubbles”, 10);
doggieList[3] = new Dog(“Mallory”, 2, false);
Unknown Fido Bubbles Mallory
0 3 10 2
true true true false
Another way to create an array of objects is to create the array and call on the constructors in one line:
Dog[] otherList = {new Dog(), new Dog(“Hulk”, 2), new Dog(“Thor”, 8, false)}
16
What do the following lines of code print to the console?
System.out.println(doggieList[1].getName());
Console:
doggieList[0].setName(“Peaches”);
Fido
System.out.println(doggieList[0].getName());
for(int i = 0; i < doggieList.length; i++){ Peaches
doggieList[i].setAge(doggieList[i].getAge() + 1); 1 4 11 3
}
for(Dog puppy : doggieList){
System.out.print(puppy.getAge() + “ “);
}
17