Java Lesson 14: ArrayLists

Advertisements

Hello everybody,

Michael here, and today I’ll post a Java lesson-my first one in nearly six months! Today’s lesson will be on ArrayLists in Java. What exactly is an ArrayList? Well, here’s an example:

package lesson14;
import java.util.ArrayList;

public class ArrayListsDemo
{
public static void main (String[] args)
{
ArrayList<String> cities = new ArrayList<String>();
}
}

An ArrayList is basically a resizable array. See, in Java, you can’t add/remove elements from an array without creating a new array (which interestingly isn’t the case with Python arrays), but with ArrayLists, you can add and remove elements as you wish. The other differences between arrays and ArrayLists include:

  • You need to import a package for ArrayLists, but not for arrays.
  • The syntax for ArrayLists is different than that for arrays. Here’s the basic structure for ArrayLists:
    • ArrayList<type> name_of_array = new ArrayList <type>()
    • All elements in an ArrayList must be of the same type!

In the example above, the ArrayList is empty. Let’s see how we can fill it up:

package lesson14;
import java.util.ArrayList;

public class ArrayListsDemo
{
public static void main (String[] args)
{
ArrayList<String> cities = new ArrayList<String>();
cities.add(“Nashville”);
cities.add(“Franklin”);
cities.add(“Chattanooga”);
cities.add(“Knoxville”);
cities.add(“Memphis”);
cities.add(“Murfreesboro”);
cities.add(“Brentwood”);
System.out.println(cities);
}
}

And here’s the output:

run:
[Nashville, Franklin, Chattanooga, Knoxville, Memphis, Murfreesboro, Brentwood]
BUILD SUCCESSFUL (total time: 1 second)

In this example, I used the add method to add the names of Tennessee cities into the cities ArrayList. Unfortunately, there isn’t a way to add several elements into the ArrayList with just one line of code; you’ll need to add all of the elements 1-by-1.

Now that we have elements in our ArrayList, let’s see how we can access them:

System.out.println(cities.get(2));

run:
[Nashville, Franklin, Chattanooga, Knoxville, Memphis, Murfreesboro, Brentwood]
Chattanooga
BUILD SUCCESSFUL (total time: 1 second)

I would use the get method to access items in the cities ArrayList.  The same element accessing array logic applies to ArrayLists, meaning that the first element corresponds to index 0, the second to index 1, and so forth. If you’re wondering why you see the entire ArrayList again, that’s because I appended the line System.out.println(cities.get(2)) to the end of the code that was present.

OK, so what if we want to change an element? Well, here’s the line of code to do that (along with the resulting output):

cities.set(5, “Pigeon Forge”);
System.out.println(cities);

[Nashville, Franklin, Chattanooga, Knoxville, Memphis, Pigeon Forge, Brentwood]
BUILD SUCCESSFUL (total time: 8 seconds)

To change an element to an ArrayList, simply use the set method and include the index of the element you wish to change as well as the new value for that index as parameters. In this example, I am changing the element at index 5 (the 6th element) to Pigeon Forge.

Now let’s see how we can remove an element:

cities.remove(3);
System.out.println(cities);

[Nashville, Franklin, Chattanooga, Memphis, Pigeon Forge, Brentwood]
BUILD SUCCESSFUL (total time: 4 seconds)

To remove an element from an ArrayList, use the remove method along with the index of the element you want to remove as a parameter. In this example, I removed the element at index 3 (the 4th element).

  • If you wanted to empty the entire ArrayList, use the clear method.

Now let’s see how we can find the size of the ArrayList (after removing the element at index 3):

System.out.println(cities.size());

6

To find the size of the ArrayList, use the size method. In this example, the size of the cities ArrayList is 6.

Ok, so let’s see how we can loop through an ArrayList:

for (int i = 0; i < cities.size(); i++)
{
System.out.println(cities.get(i));
}

Nashville
Franklin
Chattanooga
Memphis
Pigeon Forge
Brentwood
BUILD SUCCESSFUL (total time: 5 seconds)

The best way to iterate through an ArrayList is with a for loop. Now, you could possibly try to iterate through an ArrayList with a while or do-while loop, but I’d stick with a for loop.

  • You should also use the size method to indicate how many times the loop should run.

You could also use a for-each loop to iterate through the ArrayList. Here’s how you’d write it:

for (String i: cities)

{

System.out.println(i);

}

Last but not least, I want to show you guys a cool little trick for ArrayLists that you can’t use for regular arrays. But first, you’d have to import the Collections class. Let me demonstrate:

import java.util.Collections;

Collections.sort(cities);
for (String i: cities)
{
System.out.println(i);
}

Brentwood
Chattanooga
Franklin
Memphis
Nashville
Pigeon Forge
BUILD SUCCESSFUL (total time: 2 seconds)

To sort the items in an ArrayList, first import java.util.Collections. To sort the elements, use the line Collections.sort(name of ArrayList) along with a for loop (or for-each loop, which I used here). You must loop through the ArrayList after sorting it, otherwise the sorting won’t work.

ArrayLists can either be sorted numerically or alphabetically (depending on the elements in your ArrayList). From what I tried, it seems like the Collections.sort method can only sort either in ascending order (for numerical ArrayLists) or alphabetical order (for non-numerical ArrayLists). I’m not sure if ArrayLists can be sorted in descending numerical order or reverse alphabetical order, but then again there could be methods for accomplishing these types of sorts.

Thanks for reading,

Michael

Leave a ReplyCancel reply