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:
- Creating and using arrays
- Accessing and modifying array elements
- Introduction to ArrayLists
- Adding, removing, and accessing elements in ArrayLists
- Converting between arrays and ArrayLists
Let's get started with organizing our data!
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.
Let's open the file called
ArrayDemo.javain 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
mainmethod is where our program starts executing.Now, let's declare and initialize an array of integers. Add the following line inside the
mainmethod:int[] numbers = {1, 2, 3, 4, 5};This line creates an array of integers named
numbersand initializes it with the values 1, 2, 3, 4, and 5. The square brackets[]tell Java thatnumbersis an array.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.lengthgives us the size of the array, andnumbers[i]accesses the element at indexi.
Save the file, then compile and run the program:
javac ~/project/ArrayDemo.java java -cp ~/project ArrayDemoYou 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: 5Now, 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.
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.
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
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
mainmethod: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.
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.
Open the file called
ArrayListDemo.javain your project directory.import java.util.ArrayList; public class ArrayListDemo { public static void main(String[] args) { // We'll add our code here } }Note the
importstatement at the top. This tells Java that we want to use the ArrayList class in our program.Now, let's create an ArrayList of Strings. Add this line inside the
mainmethod: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.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.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.
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, andget(index)retrieves the element at the specified index.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.Unlike arrays, ArrayLists allow us to insert elements at any position using the
add(index, element)method. This is different fromset()which we saw earlier. Let's see howadd()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]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.
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.Save the file, then compile and run the program:
javac ~/project/ArrayListDemo.java java -cp ~/project ArrayListDemoYou 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.
Open the file called
ConversionDemo.javain 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.
Let's start by converting an array to an ArrayList. Add this code inside the
mainmethod: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 aList. Note that this creates a fixed-size list backed by the original array.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.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 passnew Integer[0]as an argument, which acts as a hint for the type and size of the array to be created.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);Save the file, then compile and run the program:
javac ~/project/ConversionDemo.java java -cp ~/project ConversionDemoYou 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:
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
- We created and initialized arrays using the syntax
ArrayLists:
- We created ArrayLists using
ArrayList<String> fruits = new ArrayList<>(); - We learned how to add elements with
add(), remove elements withremove(), and access elements withget() - We used methods like
size(),set(), andcontains()to work with ArrayLists - We saw that ArrayLists can grow and shrink dynamically, offering more flexibility than arrays
- We created ArrayLists using
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
- We converted arrays to ArrayLists using
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.



