Java Arrays and ArrayLists

JavaJavaBeginner
Practice Now

Introduction

In this lab, we'll dive into two fundamental data structures in Java: Arrays and ArrayLists. These structures allow us to store and manipulate collections of data, which is crucial for many programming tasks. We'll start with the basic array, then move on to the more flexible ArrayList. By the end of this lab, you'll be able to create, manipulate, and work with both arrays and ArrayLists in Java.

We'll cover:

  1. Creating and using arrays
  2. Accessing and modifying array elements
  3. Introduction to ArrayLists
  4. Adding, removing, and accessing elements in ArrayLists
  5. Converting between arrays and ArrayLists

Let's get started with organizing our data!


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java/ObjectOrientedandAdvancedConceptsGroup -.-> java/generics("`Generics`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/arraylist("`ArrayList`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/DataStructuresGroup -.-> java/arrays_methods("`Arrays Methods`") java/DataStructuresGroup -.-> java/collections_methods("`Collections Methods`") subgraph Lab Skills java/generics -.-> lab-413820{{"`Java Arrays and ArrayLists`"}} java/arraylist -.-> lab-413820{{"`Java Arrays and ArrayLists`"}} java/arrays -.-> lab-413820{{"`Java Arrays and ArrayLists`"}} java/data_types -.-> lab-413820{{"`Java Arrays and ArrayLists`"}} java/variables -.-> lab-413820{{"`Java Arrays and ArrayLists`"}} java/arrays_methods -.-> lab-413820{{"`Java Arrays and ArrayLists`"}} java/collections_methods -.-> lab-413820{{"`Java Arrays and ArrayLists`"}} end

Creating and Using Arrays

Arrays are a fundamental data structure in Java that allow you to store multiple elements of the same type. Think of an array like a row of boxes, where each box can hold one item of a specific type.

  1. Let's open the file called ArrayDemo.java in your project directory.

    public class ArrayDemo {
        public static void main(String[] args) {
            // We'll add our code here
        }
    }

    This is the basic structure of our Java program. The main method is where our program starts executing.

  2. Now, let's declare and initialize an array of integers. Add the following line inside the main method:

    int[] numbers = {1, 2, 3, 4, 5};

    This line creates an array of integers named numbers and initializes it with the values 1, 2, 3, 4, and 5. The square brackets [] tell Java that numbers is an array.

  3. Let's print out the elements of our array. Add these lines after the array declaration:

    System.out.println("The elements of the array are:");
    for (int i = 0; i < numbers.length; i++) {
        System.out.println("Element at index " + i + ": " + numbers[i]);
    }

    This code uses a for loop to iterate through the array. numbers.length gives us the size of the array, and numbers[i] accesses the element at index i.

    alt text
  4. Save the file, then compile and run the program:

    javac ~/project/ArrayDemo.java
    java -cp ~/project ArrayDemo

    You should see output similar to this:

    The elements of the array are:
    Element at index 0: 1
    Element at index 1: 2
    Element at index 2: 3
    Element at index 3: 4
    Element at index 4: 5
  5. Now, let's calculate the sum of all elements in the array. Add this code after the previous loop:

    int sum = 0;
    for (int number : numbers) {
        sum += number;
    }
    System.out.println("The sum of the elements is: " + sum);

    This code uses an enhanced for loop (also known as a for-each loop) to iterate through the array. It's a simpler way to go through all elements when you don't need the index.

  6. Finally, let's find the maximum value in the array. Add this code:

    int max = numbers[0];
    for (int i = 1; i < numbers.length; i++) {
        if (numbers[i] > max) {
            max = numbers[i];
        }
    }
    System.out.println("The maximum value in the array is: " + max);

    This code starts by assuming the first element is the maximum, then compares each subsequent element to the current max, updating max if a larger value is found.

  7. Save, compile, and run the program again. You should see the additional output:

    The sum of the elements is: 15
    The maximum value in the array is: 5
    alt text
  8. Arrays in Java are fixed in size, but we can modify their elements. Let's change an element and print the modified array. Add this code at the end of the main method:

    numbers[2] = 10;
    System.out.println("\nAfter modifying the third element:");
    for (int number : numbers) {
        System.out.print(number + " ");
    }
    System.out.println();

    This changes the value of the third element (index 2) to 10, then prints the modified array.

  9. Save, compile, and run the program one more time. You should see the additional output:

    After modifying the third element:
    1 2 10 4 5

Congratulations! You've now created an array, accessed its elements, performed calculations with its values, and modified an element. Remember, arrays in Java are fixed in size, meaning once you create an array, you can't change its length. However, you can change the values of its elements.

Introduction to ArrayLists

Now that we've worked with arrays, let's introduce ArrayLists. ArrayLists are part of the Java Collections Framework and provide a more flexible way to work with lists of objects. Unlike arrays, ArrayLists can grow or shrink in size dynamically.

  1. Open the file called ArrayListDemo.java in your project directory.

    import java.util.ArrayList;
    
    public class ArrayListDemo {
        public static void main(String[] args) {
            // We'll add our code here
        }
    }

    Note the import statement at the top. This tells Java that we want to use the ArrayList class in our program.

  2. Now, let's create an ArrayList of Strings. Add this line inside the main method:

    ArrayList<String> fruits = new ArrayList<>();

    This creates an empty ArrayList that can hold String objects. The <String> part is called a "generic" and specifies the type of elements the ArrayList will contain.

  3. Let's add some elements to our ArrayList. Add these lines:

    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Cherry");

    The add() method appends elements to the end of the list.

  4. Now, let's print our ArrayList. Add this code:

    System.out.println("Fruits in the list:");
    for (String fruit : fruits) {
        System.out.println(fruit);
    }

    This uses an enhanced for loop to iterate through the ArrayList, similar to what we did with arrays.

    Tips: You can compile and run your program at any time to see the output. Or, you can continue adding more code and run it all at the end.

  5. ArrayLists have many useful methods. Let's try a few. Add this code:

    System.out.println("\nNumber of fruits: " + fruits.size());
    System.out.println("The second fruit is: " + fruits.get(1));

    size() returns the number of elements in the ArrayList, and get(index) retrieves the element at the specified index.

  6. We can also replace elements in an ArrayList using the set() method. Add this code:

    // Before: [Apple, Banana, Cherry]
    fruits.set(1, "Blueberry");    // Replaces "Banana" with "Blueberry"
    System.out.println("\nAfter replacing the second fruit:");
    System.out.println(fruits);     // [Apple, Blueberry, Cherry]

    set(index, element) replaces the element at the specified index with a new element. The ArrayList size remains the same.

  7. Unlike arrays, ArrayLists allow us to insert elements at any position using the add(index, element) method. This is different from set() which we saw earlier. Let's see how add() works:

    // Before: [Apple, Blueberry, Cherry]
    fruits.add(1, "Blackberry");
    System.out.println("\nAfter inserting Blackberry at index 1:");
    System.out.println(fruits);
    // After: [Apple, Blackberry, Blueberry, Cherry]

    Let's understand what happened:

    • add(1, "Blackberry") inserts "Blackberry" at index 1
    • The existing elements at index 1 and beyond (Blueberry, Cherry) are automatically shifted one position to the right
    • The ArrayList size increases by 1
    • This is different from set() which would replace the existing element without shifting or changing the size

    To help visualize the difference:

    // Using add(index, element) - inserts and shifts
    fruits.add(1, "Blackberry");    // [Apple, Blackberry, Blueberry, Cherry]
    
    // Using set(index, element) - replaces without shifting
    fruits.set(1, "Blackberry");    // [Apple, Blackberry, Cherry]
  8. We can also remove elements from an ArrayList. Add this code:

    fruits.remove("Cherry");
    System.out.println("\nAfter removing Cherry:");
    System.out.println(fruits);

    This removes the first occurrence of "Cherry" from the ArrayList. When an element is removed, any subsequent elements are shifted to the left to fill the gap.

  9. Finally, let's check if certain elements are in our ArrayList:

    System.out.println("\nDoes the list contain Apple? " + fruits.contains("Apple"));
    System.out.println("Does the list contain Cherry? " + fruits.contains("Cherry"));

    The contains() method checks if the ArrayList contains a specific element and returns a boolean value.

  10. Save the file, then compile and run the program:

    javac ~/project/ArrayListDemo.java
    java -cp ~/project ArrayListDemo

    You should see output similar to this:

    Fruits in the list:
    Apple
    Banana
    Cherry
    
    Number of fruits: 3
    The second fruit is: Banana
    
    After replacing the second fruit:
    [Apple, Blueberry, Cherry]
    
    After inserting Blackberry at index 1:
    [Apple, Blackberry, Blueberry, Cherry]
    
    After removing Cherry:
    [Apple, Blackberry, Blueberry]
    
    Does the list contain Apple? true
    Does the list contain Cherry? false

Congratulations! You've now created an ArrayList, added and removed elements, accessed elements by index, and used various ArrayList methods. You've learned the important distinctions between operations like add() which inserts and shifts elements, and set() which replaces elements. ArrayLists offer more flexibility than arrays, as they can grow and shrink as needed. This makes them very useful when you don't know in advance how many elements you'll be working with.

Converting Between Arrays and ArrayLists

Sometimes you might need to convert between arrays and ArrayLists. Java provides convenient methods to do this. Let's explore how to convert an array to an ArrayList and vice versa.

  1. Open the file called ConversionDemo.java in your project directory.

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    public class ConversionDemo {
        public static void main(String[] args) {
            // We'll add our code here
        }
    }

    Note the import statements at the top. We're importing classes we'll need for our conversions.

  2. Let's start by converting an array to an ArrayList. Add this code inside the main method:

    String[] colorArray = {"Red", "Green", "Blue"};
    List<String> colorList = Arrays.asList(colorArray);
    
    System.out.println("Array converted to ArrayList:");
    System.out.println(colorList);

    Arrays.asList() converts an array to a List. Note that this creates a fixed-size list backed by the original array.

  3. Let's modify the ArrayList and see what happens to the original array. Add this code:

    colorList.set(1, "Yellow");
    
    System.out.println("\nAfter modifying the ArrayList:");
    System.out.println(colorList);
    System.out.println("Original array after ArrayList modification:");
    System.out.println(Arrays.toString(colorArray));

    Arrays.toString() is a convenient method to print an array.

  4. Now, let's convert an ArrayList to an array. Add this code:

    ArrayList<Integer> numberList = new ArrayList<>();
    numberList.add(1);
    numberList.add(2);
    numberList.add(3);
    
    Integer[] numberArray = numberList.toArray(new Integer[0]);
    
    System.out.println("\nArrayList converted to array:");
    System.out.println(Arrays.toString(numberArray));

    We use the toArray() method of ArrayList to convert it to an array. We pass new Integer[0] as an argument, which acts as a hint for the type and size of the array to be created.

  5. Finally, let's modify the array and see if it affects the ArrayList. Add this code:

    numberArray[0] = 100;
    System.out.println("\nAfter modifying the array:");
    System.out.println("Array: " + Arrays.toString(numberArray));
    System.out.println("ArrayList: " + numberList);
  6. Save the file, then compile and run the program:

    javac ~/project/ConversionDemo.java
    java -cp ~/project ConversionDemo

    You should see output similar to this:

    Array converted to ArrayList:
    [Red, Green, Blue]
    
    After modifying the ArrayList:
    [Red, Yellow, Blue]
    Original array after ArrayList modification:
    [Red, Yellow, Blue]
    
    ArrayList converted to array:
    [1, 2, 3]
    
    After modifying the array:
    Array: [100, 2, 3]
    ArrayList: [1, 2, 3]

This demonstration shows how arrays and ArrayLists can be converted into each other. It's important to note the difference in behavior:

  • When you convert an array to a List using Arrays.asList(), the resulting List is backed by the original array. This means changes to the List will be reflected in the array, and vice versa.
  • When you convert an ArrayList to an array using toArray(), you create a new array that is independent of the ArrayList. Changes to this new array will not affect the original ArrayList.

Understanding these conversions and their behaviors is crucial when working with different collection types in Java, especially when interfacing with APIs or libraries that might prefer one type over the other.

Summary

In this lab, we've explored two fundamental data structures in Java: Arrays and ArrayLists. Let's recap what we've learned:

  1. Arrays:

    • We created and initialized arrays using the syntax int[] numbers = {1, 2, 3, 4, 5};
    • We learned how to access array elements using index notation, like numbers[0]
    • We iterated through arrays using both traditional for loops and enhanced for loops
    • We performed calculations with array elements, like finding the sum and maximum value
    • We saw that arrays have a fixed size, but we can modify their elements
  2. ArrayLists:

    • We created ArrayLists using ArrayList<String> fruits = new ArrayList<>();
    • We learned how to add elements with add(), remove elements with remove(), and access elements with get()
    • We used methods like size(), set(), and contains() to work with ArrayLists
    • We saw that ArrayLists can grow and shrink dynamically, offering more flexibility than arrays
  3. Converting between Arrays and ArrayLists:

    • We converted arrays to ArrayLists using Arrays.asList()
    • We converted ArrayLists to arrays using the toArray() method
    • We observed the different behaviors when modifying converted collections

Arrays and ArrayLists are essential tools in Java programming. Arrays are great for working with a fixed number of elements and can be more efficient in terms of memory usage. ArrayLists, on the other hand, offer more flexibility and a rich set of methods for manipulating the collection.

As you continue your Java journey, you'll find yourself using both arrays and ArrayLists frequently. The choice between them often depends on your specific needs - if you know the exact number of elements you'll be working with, an array might be preferable. If you need a dynamic collection that can grow or shrink, or if you need the additional methods provided by ArrayLists, then an ArrayList would be the better choice.

Other Java Tutorials you may like