• Lessons Home
Topics
Community
  1. Lessons
  2. Apex Collections
  3. Lists
  4. Adding and Removing Elements

      Adding and Removing Elements

      Adding and Removing Elements

      Lists are not fixed in size. After you create a list you can grow it by adding elements and shrink it by removing them. The list keeps its order as it changes.

      Adding to the End

      The add method places a value at the end of the list, so the list grows by one each time you call it:

      List<String> queue = new List<String>();
      queue.add('Ada');
      queue.add('Grace');
      // queue is now Ada, Grace
      

      Removing by Position

      The remove method takes an index and removes the element at that position. Every element after it shifts down to fill the gap, and the list becomes one shorter:

      List<String> letters = new List<String>{ 'a', 'b', 'c' };
      letters.remove(1); // removes 'b'
      // letters is now a, c
      

      After the removal, letters.get(1) returns c, because c moved from index 2 down to index 1.

      Order Is Preserved

      Adding and removing never scrambles the remaining items. Values you do not touch stay in the same relative order, which makes a list a reliable way to manage a changing sequence of values.

      Why This Matters

      Real programs rarely know every value ahead of time. Being able to add results as they arrive and remove items you no longer need lets a single list represent data that changes while your code runs.

      Apex Code Editor
      Sign in to Submit

      Welcome to Lightning Challenge!

      How It Works

      • • Write your solution in the code editor
      • • Connect your Salesforce org to test
      • • Submit to check if your solution passes
      • • Use hints if you get stuck

      Note

      Complete this lesson challenge to earn points and track your progress. The code editor allows you to implement your solution, and the tests will verify if your code meets the requirements.

      Wally Assistant

      Wally can't hear you

      Please sign in to access the AI Assistant

      Sign In