Activity 11.3.1.
What does the following code do? Guess before you run it. Then, add another enhanced for each loop that computes the product of all the elements in myList by multiplying them. Print out the product after the new loop.
ArrayList
is when iteration (a loop) is used to access all or an ordered sequence of the elements in the ArrayList
. Just like with arrays, we can use while
loops, indexed for
loops, or enhanced for
loops to traverse an ArrayList
. In a later lesson, weβll also talk about recursion which is when a method calls itself over again which is another way you can traverse an array or ArrayList
. In this lesson, weβll focus on using loops.
for
loop to traverse all of the items in an ArrayList
, just like you do with an array when you only care about the values in the list and not their indices. An example is shown in the main
method below.
for
loop if you want to add or remove elements while traversing an ArrayList
. If the size of an ArrayList
is modified, such as by calling the add
or remove
methods, while it is being looped over, it will cause the loop to throw a ConcurrentModificationException
. If you need to modify an ArrayList
while looping over it, youβll need to use a regular while
or for
loop.
for
loop to process list elements accessed using an index. ArrayList
indices starts at 0 just like array indices, but instead of using the index operator []
to access elements, you use the get(index)
method to get the value at the index and set(index,value)
to set the element at an index to a new value.
IndexOutOfBoundsException
, similar to the ArrayIndexOutOfBoundsException
thrown if you use the index operator on an array with an index out of bounds for that array.
IndexOutOfBoundsException
. Can you fix it?
while
loop and an object-oriented approach where the list is a field of the current object and an instance method rather than a class (static) method loops through the list.
nums
has been created as an ArrayList
object and it initially contains the following Integer
values [0, 0, 4, 2, 5, 0, 3, 0]. What will nums
contain as a result of executing numQuest
?
ArrayList<Integer> list1 = new ArrayList<Integer>();
private ArrayList<Integer> nums;
// precondition: nums.size() > 0;
// nums contains Integer objects
public void numQuest()
{
int k = 0;
Integer zero = new Integer(0);
while (k < nums.size())
{
if (nums.get(k).equals(zero))
nums.remove(k);
k++;
}
}
java.nio.file
java.nio.file
package (nio stands for new input/output), added in Java version 7, provides a better and easier way to read in files. The Files
class in this package has a method called readAllLines
that reads all of the lines in a file and returns them as a List
of String
objects. The readAllLines
method throws an IOException
if the file cannot be read. (List
is an interface. Interfaces are not on the AP CSA exam but are quite common in actual Java programming. For now all you need to know is that all the methods weβve talked about using with ArrayList
you can use on any List
such as the one returned by readAllLines
.)
import java.nio.file.*;
...
// This connects and reads in the file in 1 line of code!
// It needs to be in a method that throws or handles IOException
List<String> lines = Files.readAllLines(Paths.get("data.txt"));
readAllLines
is almost certainly using an ArrayList
which is a kind of List
. The advantage of storing the lines in a dynamic data structure like an ArrayList
, instead of an array, is that you do not need to know how many lines you are going to store when you create the ArrayList
the way you do when you create an array. The ArrayList
can then grow in size as needed. (If you absolutely need an array, you can convert the List
to an array declared to be the correct size with myArray = lines.toArray(myArray);
)
Files.readAllLines
into a List<String>
named lines
. Add a loop that prints out the first 10 pokemon.
ArrayList
. For example, here is an ArrayList
of Student
s. Letβs write some loops that traverse the ArrayList
to print out each Student
by implicitly calling its toString()
method. Weβll also write a method that filters the ArrayList
to print out only the students who have a GPA higher than 3.5 for the honor roll.
// get the name of the 0's student
String name = students.get(0).getName();
// get the GPA of the student at index i
double gpa = students.get(i).getGPA();
WordPair
that can store pairs of words.
class WordPair
{
private String word1;
private String word2;
public WordPair(String word1, String word2)
{
this.word1 = word1;
this.word2 = word2;
}
public String getFirst()
{
return word1;
}
public String getSecond()
{
return word2;
}
public String toString()
{
return "(" + word1 + ", " + word2 + ")";
}
}
ArrayList
of WordPair
objects below. Look at the StudentList
example above for help.
WordPairsList
below, you will write the constructor which takes the array of words and pairs them up as shown in the figure. You will need nested loops to pair each element with the rest of the elements in the list.
words
array for the first word in the word pair (for loop from index i = 0
to length-1
)
i + 1
for the second word in the word pair (for loop from index j = i + 1
to length
)
WordPairsList
below which will add pairs of words from a given array to the ArrayList
. Then, complete the method numMatches()
as described below this exercise.
numMatches
that counts and returns the number of pairs where the first word is the same as the second word. For example, if the word array is ["hi","bye","hi"]
, the pairs generated would be ["hi","bye"]
, ["hi","hi"]
, and ["bye","hi"]
. In the second pair ["hi","hi"]
, the first word is the same as the second word, so numMatches
would return 1.
ArrayList
allPairs
and for each WordPair
in allPairs
, it checks to see if its first word (using the getFirst
method) equals the second word (using the getSecond
method). If there is a match, it increments a counter which it returns at the end of the method. To test this method, add another βthereβ into the words array and then uncomment the call to numMatches
.
ArrayList
is when iteration or recursive statements are used to access all or an ordered sequence of the elements in an ArrayList
.
ArrayList
s can be traversed with an enhanced for
loop, a while
loop, or a regular for
loop using an index.
ArrayList
requires the use of special techniques to avoid skipping elements (since remove
moves all the elements above the removed index down.)
IndexOutOfBoundsException
. (The indices for an ArrayList
start at 0 and end at the number of elements β 1).
ArrayList
while traversing it using an enhanced for
loop can result in a ConcurrentModificationException
. Therefore, when using an enhanced for
loop to traverse an ArrayList
, you should not add or remove elements.