Working with ArrayList
Constructing an ArrayList
data structure and adding/removing objects to it is a very common task in Java. In this exercise, you will create a shopping list - as represented by a list of Strings
, and add, remove and change items on the list.
This exercise is part of the course
Data Types and Exceptions in Java
Exercise instructions
- Import
ArrayList
for use in the application. - Construct a new
ArrayList
ofString
s and set theshopList
variable to it. - Add a second
"milk"
to the shopping list. - Change
"bread"
to"rye-bread"
on the shopping list.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
// Import ArrayList
____ ____.____.____;
public class Shopping {
public static void main(String[] args) {
// Create an ArrayList of Strings using parameterized constructor
____<____> shopList = ____ ____<____>();
shopList.add("milk");
shopList.add("eggs");
shopList.add("bread");
// Add milk to the list again
shopList.____("____");
System.out.println(shopList);
// Change bread to rye-bread in the list
shopList.____(____, "____");
shopList.remove("milk");
System.out.println(shopList);
System.out.println(shopList.size());
}
}