< Unit 6 - ArrayLists and String Methods ('22-'23)

Lesson 6: Removing Elements

45 minutes

Overview

How is removing data from an ArrayList different from removing data from an array?

Students explore the functionality of the remove() method in the ArrayList class and identify potential errors when attempting to remove items while traversing the list. Students learn about stop word removal and practice removing elements from an ArrayList.

CSA Conceptual Framework
      • CON-2.J.1 - There are standard ArrayList algorithms that utilize traversals to: • Insert elements • Delete elements • Apply the same standard algorithms that are used with 1D arrays
      • VAR-1.E.12 - The following String methods and constructors—including what they do and when they are used—are part of the Java Quick Reference: • String(String str) — Constructs a new String object that represents the same sequence of characters as str • int length() — Returns the number of characters in a String object • String substring(int from, int to) — Returns the substring beginning at index from and ending at index to - 1 • String substring(int from) — Returns substring(from, length()) • int indexOf(String str) — Returns the index of the first occurrence of str; returns -1 if not found • boolean equals(String other) — Returns true if this is equal to other; returns false otherwise • int compareTo(String other) — Returns a value < 0 if this is less than other; returns zero if this is equal to other; returns a value > 0 if this is greater than other
      • VAR-2.D.7 - The following ArrayList methods— including what they do and when they are used—are part of the Java Quick Reference: • int size() - Returns the number of elements in the list • boolean add(E obj) - Appends obj to end of list; returns true • void add(int index, E obj) - Inserts obj at position index (0 <= index <= size), moving elements at position index and higher to the right (adds 1 to their indices) and adds 1 to size • E get(int index) - Returns the element at position index in the list • E set(int index, E obj) —  Replaces the element at position index with obj; returns the element formerly at position index • E remove(int index) — Removes element from position index, moving elements at position index + 1 and higher to the left (subtracts 1 from their indices) and subtracts 1 from size; returns the element formerly at position index
      • VAR-2.E.2 - Deleting elements during a traversal of an ArrayList requires using special techniques to avoid skipping elements.
      • VAR-2.E.4 - Changing the size of an ArrayList while traversing it using an enhanced for loop can result in a ConcurrentModificationException being thrown. Therefore, when using an enhanced for loop to traverse an ArrayList, you should not add or remove elements.

Agenda

Objectives

Students will be able to:
  • Explain the cause of a ConcurrentModificationException
  • Use methods in the ArrayList class to remove elements

Preparation

  • Check the Teacher's Lounge for verified teachers on the CSA Forum to find additional strategies or resources shared by fellow teachers

Links

Heads Up! Please make a copy of any documents you plan to share with students.

For the students

Vocabulary

  • ConcurrentModificationException - An exception that occurs when code attempts to change the size of an ArrayList while traversing it using an enhanced for loop
  • Stop Word - A word that is filtered out of a list before or after processing text
  • Stop Word Removal - The process of removing commonly used words from a list before or after processing text

Teaching Guide

Warm Up (10 minutes)

The Social Media Dilemma

Remarks

You are writing an algorithm for your favorite social media app. This algorithm uses an array to store the names of every user someone is following. We know that people sometimes "break up" with friends for whatever reason. Therefore, the user needs the ability to unfollow or remove a friend from their list.

Group: Place students in groups of three to four.

Do This: Have students develop a solution to the Social Media Dilemma.

Teaching Tip

Encourage groups to plan their solutions using pseudocode, drawings, diagrams, or even acting it out.

Discuss: Click through the animated slide to display the prompts. Use the Retrieve-Pair-Share strategy to discuss the prompts.

  • What challenges did you run into with using an array for this problem?
  • What would you like to be able to do that an array doesn’t allow?
  • Given what you know about the add() method for an ArrayList, how do you think an ArrayList handles removing items?

Discussion Goal: Students identify that they cannot easily remove elements directly from the same array, as arrays are immutable. Students note that they would like to remove items from the array without leaving any empty locations. Students guess there might be a remove() method in the ArrayList class to remove items from a list and resize it accordingly.

Teaching Tip

Students will likely have a solution similar to one of the following:

  • Replace the item with the next item (for example, the item at index 1 replaces the item at index 0) and so on. The final item in the array becomes null.
  • Create a second array that was the correct size, and set the array's values with the values to be kept from the initial array.

If students struggle to get started with this problem, consider prompting them with questions to guide them towards one of these two solutions.

Activity (30 minutes)

Removing with a For Loop (10 minutes)

Remarks

It is not easy to remove elements from an array. However, an ArrayList gives us a way to solve this problem. Let's take a look at how the remove() method in the ArrayList class works.

Do This: Review the lesson objectives.

Group: Place students in pairs.

Do This: Direct students to Level 1 on Code Studio to investigate the program with a partner. Students make the changes to the program as prompted.

Discuss: Click through the animated slide to display the prompts.

  • What do you notice about the code in this program?
  • What do you wonder about the code in this program?

Discussion Goal: Students notice that the remove() method removes items from the ArrayList and updates the size accordingly. Students may wonder how they could use this method in other algorithms or scenarios.

Remarks

As we saw in this program, the remove() method removes elements from the specified index. The elements in the ArrayList that are at the specified index and higher are then shifted to the left by one place, subtracting one from their indices and subtracting one from the size. We also saw that the value that was at the specified index is returned from calling the remove() method.

Discuss: Use the Hold That Thought strategy to discuss the prompt.

  • How is the remove() method different from how we would remove items from an array?

Discussion Goal: Students identify that since arrays are immutable, they would need to set the item's index to remove to null to remove it and then shift the other items in the array. Doing so would leave an empty index. In an ArrayList, using remove() allows the item to be completely removed, shifting the rest of the items up in the ArrayList.

Display: Show the video – Removing Data from an ArrayList.

Remarks

When we use the remove() method to remove an element from a specified index, the elements that are at the specified index and higher are then shifted to the left by one place. This can result in elements being skipped during traversal since the loop control variable continues to increase by one. We need a way to avoid skipping elements when an element is removed from the list.

Do This: Demonstrate using remove() with a for loop and how to avoid skipping elements.

Removing with an Enhanced For Loop (10 minutes)

Remarks

Like with 1D and 2D arrays, we can also use an enhanced for loop to traverse an ArrayList. Let's look at some similarities and differences between using enhanced for loops with arrays and ArrayLists.

Do This: Direct students to Level 2 on Code Studio to predict the outcome of the program, then run the program to compare their predictions to the actual outcome.

Discuss: Use the Hold That Thought strategy to discuss the prompt.

  • What differences do you notice between these two pieces of code?

Discussion Goal: Students notice that while the structures look similar, the enhanced for loop used with an array uses a primitive data type (int) whereas the enhanced for loop with an ArrayList uses an object (Integer).

Do This: Direct students to Level 3 on Code Studio to investigate the program with a partner. Students make the changes to the program as prompted.

Do This: Explain ConcurrentModificationException and how to avoid it.

Stop Word Removal (10 minutes)

Do This: Click through the animated slide to define stop word and stop word removal and demonstrate how it is applied in natural language processing.

Remarks

You learned in a previous lesson about using the equals() method to compare objects for equality, which includes Strings. We can use this to find and remove stop words.

Do This: Direct students to Level 4 on Code Studio to complete Levels 4 and 5. On Level 4, students debug code that results in a ConcurrentModificationException. On Level 5, students complete a choice level to use the remove() method to remove values from an ArrayList.

Wrap Up (5 minutes)

Revisiting the Social Media Dilemma

Discuss: Use the Retrieve-Pair-Share strategy to discuss the prompt.

  • How would we solve our Social Media Dilemma using ArrayList instead of an array? Is this problem easier to solve with an array or ArrayList? Why?

Discussion Goal: Students describe using a loop to traverse an ArrayList of friends and removing friends to be unfollowed. Students note that this problem is much easier with an ArrayList because the remove() takes out the element and shifts the items in the list in one step.

Do This: Review the concepts covered in this lesson.

Display: Key Vocabulary


Assessment: Check for Understanding

Check For Understanding Question(s) and solutions can be found in each lesson on Code Studio. These questions can be used for an exit ticket.

AP Classroom Topic Questions

To assign questions from the AP Classroom Question Bank that align with this lesson, create a custom quiz in AP Classroom by searching the Question Bank for the Essential Knowledge statements listed at the top of this lesson plan. You can find instructions and video demonstrations to do this on AP Central.

The following Topic Questions in AP Classroom can be assigned as a formative assessment for this lesson:

  • Topic Questions 7.2
  • Topic Questions 7.3

Note: Some Learning Objectives and Essential Knowledge statements in the suggested Topic Questions are covered in later units.

Creative Commons License (CC BY-NC-SA 4.0).

This work is available under a Creative Commons License (CC BY-NC-SA 4.0).

If you are interested in licensing Code.org materials for commercial purposes contact us.