Arrays and ArrayLists

sdfljadslfjslfj

/*
We have now seen how to store a list of values in arrays. We can use this knowledge to make organized programs with more complex variables.

Throughout the lesson, we have learned about:

Creating arrays explicitly, using { and }.
Accessing an index of an array using [ and ].
Creating empty arrays of a certain size, and filling the indices one by one.
Getting the length of an array using length.
Using the argument array args that is passed into the main() method of a class.
*/

import java.util.Arrays;

public class Classroom {

    public static void main(String[] args){
        String[] students = {"Sade", "Alexus", "Sam", "Koma"};
        double[] mathScores = new double[4];

        mathScores[0] = 94.5;
        mathScores[2] = 76.8;

        System.out.println("The number of students in the class is " + students.length);
    }
}

TODO Explain how args are passed into the program and the args arrary works.

We can also create empty arrays and then fill the items one by one. Empty arrays have to be initialized with a fixed size:

String[] menuItems = new String[5];

Once you declare this size, it cannot be changed! This array will always be of size 5.

When we use new to create an empty array, each element of the array is initialized with a specific value depending on what type the element is:

Data Type Initialized Value
int 0
double 0.0
boolean false
Reference null
String[] my_names = new String[5];
int[] my_ages = new int[5];

Because a String is a reference to an Object, mynames will contain five nulls. myages will contain five 0s to begin with.

ArrayLists

To create an ArrayList, we need to declare the type of objects it will hold, just as we do with arrays:

ArrayList<String> babyNames;

We use angle brackets < and > to declare the type of the ArrayList. These symbols are used for generics. Generics are a Java construct that allows us to define classes and objects as parameters of an ArrayList. For this reason, we can’t use primitive types in an ArrayList:

// This code won't compile:
ArrayList<int> ages;

// This code will compile:
ArrayList<Integer> ages;

The <Integer> generic has to be used in an ArrayList instead. You can also use <Double> and <Char> for types you would normally declare as doubles or chars. We can initialize to an empty ArrayList using the new keyword:

// Declaring:
ArrayList<Integer> ages;
// Initializing:
ages = new ArrayList<Integer>();

// Declaring and initializing in one line:
ArrayList<String> babyNames = new ArrayList<String>();

Adding Items

Now we have an empty ArrayList, but how do we get it to store values? ArrayList comes with an add() method which inserts an element into the structure. There are two ways we can use add(). If we want to add an element to the end of the ArrayList, we’ll call add() using only one argument that represents the value we are inserting. In this example, we’ll add objects from the Car class to an ArrayList called carShow:

ArrayList<Car> carShow = new ArrayList<Car>();

carShow.add(ferrari);
// carShow now holds [ferrari]
carShow.add(thunderbird);
// carShow now holds [ferrari, thunderbird]
carShow.add(volkswagon);
// carShow now holds [ferrari, thunderbird, volkswagon]

If we want to add an element at a specific index of our ArrayList, we’ll need two arguments in our method call: the first argument will define the index of the new element while the second argument defines the value of the new element:

// Insert object corvette at index 1
carShow.add(1, corvette);
// carShow now holds [ferrari, corvette, thunderbird, volkswagon]

// Insert object porsche at index 2
carShow.add(2, porsche);
// carShow now holds [ferrari, corvette, porsche, thunderbird, volkswagon]

By inserting a value at a specified index, any elements that appear after this new element will have their index value shift over by 1. Also, note that an error will occur if we try to insert a value at an index that does not exist. When using ArrayList methods (like add()), the reference parameters and return type of a method must match the declared element type of the ArrayList. For example, we cannot add an Integer type value to an ArrayList of String elements. We’ve discussed how to specify the element type of an ArrayList; however, it is possible to create an ArrayList that holds values of different types. In the following snippet, assortment is an ArrayList that can store different values because we do not specify its type during initialization.

ArrayList assortment = new ArrayList<>();
assortment.add("Hello"); // String
assortment.add(12); // Integer
assortment.add(ferrari); // reference to Car
// assortment holds ["Hello", 12, ferrari]

In this case, the items stored in this ArrayList will be considered Objects. As a result, they won’t have access to some of their methods without doing some fancy casting. Although this type of ArrayList is allowed, using an ArrayList that specifies its type is preferred.

Review

Nice work! You now know the basics of ArrayLists including:

  • Creating an ArrayList.
  • Adding a new ArrayList item using add().
  • Accessing the size of an ArrayList using size().
  • Finding an item by index using get().
  • Changing the value of an ArrayList item using set().
  • Removing an item with a specific value using remove().
  • Retrieving the index of an item with a specific value using indexOf().
  • Now if only there were some way to move through an array or ArrayList, item by item…
This page was last updated: not defined. Source