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.
Este exercício faz parte do curso
Data Types and Exceptions in Java
Instruções do exercício
- Import
ArrayListfor use in the application. - Construct a new
ArrayListofStrings and set theshopListvariable to it. - Add a second
"milk"to the shopping list. - Change
"bread"to"rye-bread"on the shopping list.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
// 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());
}
}