Skip to main content
Contents
Dark Mode Prev Up Next Scratch ActiveCode Profile
\(
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
Section 14.7 Assessment: Write ArrayLists
Subgoals for Writing ArrayLists.
Importing the ArrayList class
Before using ArrayList, import it from the java.util package:
import java.util.ArrayList;
Declaring an ArrayList variable
Determine the type of objects to be stored (use wrapper classes for primitives, e.g., Integer instead of int)
Determine the name of the ArrayList variable
Use syntax:
ArrayList<DataType> name;
Instantiating an ArrayList object
Use the
new
keyword with the constructor to create a new ArrayList object (When ArrayLists are instantiated, they are empty and have a size of 0.)
Adding elements to an ArrayList
To add to the end of an ArrayList, use:
listName.add(valueToBeAdded)
To add an element at a specific location in an ArrayList, use:
listName.add(index, valueToBeAdded)
where index is within the bounds 0 to
listName.size()
Accessing an element in an ArrayList
Determine the index of the element to be accessed
Use:
listName.get(index)
to retrieve the element
Ensure the index is within bounds: 0 to
listName.size() - 1
, otherwise an IndexOutOfBoundsException occurs
Changing a value in an ArrayList
Determine the index of the element to be changed
Determine the new value or expression to assign
Use:
listName.set(index, newValue)
to update the value
Ensure the index is within bounds: 0 to
listName.size() - 1
, otherwise an IndexOutOfBoundsException occurs
Decide whether accessing all elements, updating, or accessing a subset
If only
accessing elements, use an enhanced for (for-each) loop:
for (DataType item : listName)
- iterates from first to last, storing a copy of each element in
item
If updating or using indices, use a traditional for loop:
Initialize loop control variable to 0 (or
listName.size() - 1
for reverse)
Set condition:
i < listName.size()
(or
i >= 0
for reverse)
Increment or decrement loop control variable appropriately
Use Subgoals 5 or 6 to access or change values as appropriate
Passing an ArrayList as an argument
Check if the method expects an ArrayList argument (check documentation or method signature)
When calling a method, pass a reference to an ArrayList (usually variable name) as an argument in the method call.
Note: changes to elements in the ArrayList that are done inside the method will persist
Exercises Exercises
1.
Q1: The following method is intended to return a String formed by concatenating elements from the parameter
words
. The elements to be concatenated start with
startIndex
and continue through the last element of
words
and should appear in reverse order in the resulting string.
import java.util.ArrayList;
// Assume words.size() > 0 and startIndex >= 0
public String concatWords(ArrayList<String> words, int startIndex) {
String result = "";
/* missing code */
return result;
}
For example, the following code segment should print CarHouseGorilla:
ArrayList<String> things = new ArrayList<>();
things.add("Bear");
things.add("Apple");
things.add("Gorilla");
things.add("House");
things.add("Car");
System.out.println(concatWords(things, 2));
Which of the following code segments is a correct replacement for
/* missing code */
?
for (int k = startIndex; k < words.size(); k++) {
result += words.get(k) + words.get(words.size() - k - 1);
}
int k = words.size() - 1;
while (k >= startIndex) {
result += words.get(k);
k--;
}
ArrayList<String> temp = new ArrayList<>(words);
Collections.reverse(temp);
for (int k = 0; k < temp.size() - startIndex; k++) {
result += temp.get(k);
}
2.
Q2: Consider the following two methods. What is printed as a result of the call
start()
?
import java.util.ArrayList;
public void changeIt(ArrayList<String> list, int num) {
list = new ArrayList<>();
num = 0;
list.add("Zero");
}
public void start() {
ArrayList<String> words = new ArrayList<>();
words.add("One");
words.add("Two");
int value = 6;
changeIt(words, value);
System.out.println(words + " " + value);
}
3.
Q3: Consider the following two methods. What is printed as a result of the call
start()
?
import java.util.ArrayList;
public void modifyList(ArrayList<String> list, String word) {
list.add(word.substring(0, 5));
word = "Changed";
}
public void start() {
ArrayList<String> items = new ArrayList<>();
items.add("Red");
items.add("Blue");
String label = "Magenta";
modifyList(items, label);
System.out.println(items + " " + label);
}
[Red, Blue, Magen] Magenta
[Red, Blue, Changed] Changed
You have attempted
of
activities on this page.