LoslegenKostenlos loslegen

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.

Diese Übung ist Teil des Kurses

Data Types and Exceptions in Java

Kurs anzeigen

Anleitung zur Übung

  • Import ArrayList for use in the application.
  • Construct a new ArrayList of Strings and set the shopList variable to it.
  • Add a second "milk" to the shopping list.
  • Change "bread" to "rye-bread" on the shopping list.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

// 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());
	}
}
Code bearbeiten und ausführen