Skip to main content
Contents
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 13.7 ArrayList-WE3-P1
Subgoals for Evaluating ArrayLists.
Declaring and initialization of an ArrayList
Set up a one-dimensional dynamic list (initially empty or with a specified initial capacity)
Upon instantiation, an ArrayList contains zero elements initially, but elements can be added dynamically using
add()
. Elements not yet added do not exist until explicitly inserted.
Determine access or change of element, or action on entire ArrayList object, and update elements as needed (remembering assignment subgoals)
Accessing an ArrayList element
Evaluate expression within
get(index)
which will be the index for the element to be accessed
arrayListName.get(index)
returns the value stored at that index
index must be between 0 and
arrayListName.size() - 1
, inclusive; otherwise
IndexOutOfBoundsException
occurs
Changing value of an ArrayList element
Evaluate expression within
set(index, value)
which will be the index for the element to be replaced
arrayListName.set(index, value)
replaces the element at
index
with the specified
value
(remember the assignment subgoals for verifying data types and evaluating expressions)
(remember rules for index values)
Passing as argument - a copy of the reference to the instantiated ArrayList is passed to the method. This means that any changes made to the elements inside the method persist outside the method. The exception is if the argument is assigned to reference a different ArrayList inside the method.
Assignment - changes the reference to point to the ArrayList on the right-hand side of the assignment operator.
Subsection 13.7.1
Exercises Exercises
1.
Q12: Assume the following given declarations:
import java.util.ArrayList;
import java.util.Arrays;
ArrayList<Integer> beta = new ArrayList<>(Arrays.asList(12, 24, 36, 48, 60));
Evaluate these statements:
beta.set(2, beta.get(beta.get(4) / beta.get(0) - 1));
beta.set(1, beta.get(3) - beta.get(1) + 6);
beta.set(3, beta.get(beta.get(4) % beta.get(0)));
Give the contents of ArrayList
beta
after the execution of the above statements:
For questions 13-15, give the contents of
alpha
after the execution of these statements.
import java.util.ArrayList;
import java.util.Arrays;
ArrayList<Integer> alpha = new ArrayList<>(Arrays.asList(2, 4, 6, 8, 10));
for (int i = 8; i >= 0; i -= 2)
alpha.set(i / 2, i / 2 + 1);
2.
3.
4.
You have attempted
of
activities on this page.