Java
TOPIC 47 – ARRAYLISTS
LESSON WORK
QUESTION 1 (GROUP WORK)
Do the following:
a) Create
an ArrayList<Integer> object named ali.
b) Add five
elements to the list with values 3, 4, 1, 9 and 5.
c) Output
the list to screen to verify its content.
d) Output
the size of the list to screen by using the size() method.
e) Add
another element with value 7 at the beginning of the list.
f) Output
the list to screen to verify its content.
g) Add
another element with value -1 at the end of the list.
h) Output
the list to screen to verify its content.
i) Add
another element with value 2 after element index 3 (at element index 4).
j) Output
the list to screen to verify its content.
k) Set
the value of the element with index 5 to -2.
l) Output
the list to screen to verify its content.
m) Remove
the element with index 2.
n) Output
the list to screen to verify its content.
o) Remove
the first element.
p) Output
the list to screen to verify its content.
q) Remove
the last element.
r) Output
the list to screen to verify its content.
s) Loop
through the list and increase each element's value by 1.
t) Output
the list to screen to verify its content.
TO ADD:
Sorting ArrayList
INDIVIDUAL WORK
QUESTION #1 – FILL IN THE BLANKS (SELF-CHECK)
a)
True or false. An array’s size can be changed. ______
b)
True or false. An ArrayList’s size can be changed. ______
c)
Write the statement to create an ArrayList
named frank that will hold int values.
___________________________
d)
Write the statement to create an ArrayList
named coco that will hold double values. ____________________________
e)
Write the statement to create an ArrayList
named ali that will hold Point objects.
___________________________
f)
The index of the first element in an
ArrayList is ______.
g)
If the size of an ArrayList is 10, the
index of the last element will be ______.
h)
If the size of an ArrayList is 10, what
happens if you try to get the value of the element at index 10? _______________________________
For the next few questions, assume ArrayList al already exists
and has int values stored in it.
i)
Write the statement to output the first
element in al. _________________
j)
Write the statement(s) to set the value of
element 2 to 7. ______________
k)
Write the statements to swap the values of
elements 2 and 3. ________________
l)
Write the statements to output the size of
al to screen. _____________
m)
Write the statement(s) to double the value
of the element at index 7. _________________
n)
Write the statement(s) to make the value of
element 0 become the sum of element 3 and element 4. __________________
Check your solutions here.
|
|