Java ArrayList


An ArrayList is a Resizable-array implementation of the List interface.

This class is one of the most commonly used collection in the java environment. It's so flexible and easy to use and powerful. It's power and flexibility come from the fact that ArrayList implements all optional list operations, and permits all elements, including null.

Internally an ArrayList utilizes an Array to store it's items. Because of this some developers usually refer to an ArrayList as a dynamic array.

Hence the ArrayList class provides methods to manipulate the size of the array that is used internally to store the list.

The ArrayList is roughly equivalent to Vector, except that it is unsynchronized.

While using an ArrayList keep the following in mind for the sake of performance:

  1. The size, isEmpty, get, set, iterator, and listIterator operations run in constant time.
  2. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time.
  3. All of the other operations run in linear time (roughly speaking).
  4. The constant factor is low compared to that for the LinkedList implementation.

When you instantiate an ArrayList, you get access to the ArrayList capacity for that instance. This capacity is the size of the array used to store the elements in the list. The ArrayList is always at least as large as the list size.

Then as you add more elements to an ArrayList, its capacity grows automatically. Adding an element to an ArrayList has constant amortized time cost.

You can increases your ArrayList capacity using the ensureCapacity operation. This may reduce the amount of incremental reallocation and can be useful before adding a large number of elements.

An ArrayList is a Resizable-array implementation of the List interface.

This class is one of the most commonly used collection in the java environment. It's so flexible and easy to use and powerful. It's power and flexibility come from the fact that ArrayList implements all optional list operations, and permits all elements, including null.

Internally an ArrayList utilizes an Array to store it's items. Because of this some developers usually refer to an ArrayList as a dynamic array.

Hence the ArrayList class provides methods to manipulate the size of the array that is used internally to store the list.

The ArrayList is roughly equivalent to Vector, except that it is unsynchronized.

While using an ArrayList keep the following in mind for the sake of performance:

  1. The size, isEmpty, get, set, iterator, and listIterator operations run in constant time.
  2. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time.
  3. All of the other operations run in linear time (roughly speaking).
  4. The constant factor is low compared to that for the LinkedList implementation.

When you instantiate an ArrayList, you get access to the ArrayList capacity for that instance. This capacity is the size of the array used to store the elements in the list. The ArrayList is always at least as large as the list size.

Then as you add more elements to an ArrayList, its capacity grows automatically. Adding an element to an ArrayList has constant amortized time cost.

You can increases your ArrayList capacity using the ensureCapacity operation. This may reduce the amount of incremental reallocation and can be useful before adding a large number of elements.

ArrayList API Definition

An ArrayList as a class derives from the AbstractList<E> and implements the following three interfaces:

  1. List<E> - an interface representing an ordered collection
  2. RandomAccess - Marker interface used by List implementations to indicate that they support fast (generally constant time) random access.
  3. Cloneable - A class implements the Cloneable interface to indicate to the clone() method that it is legal for that method to make a field-for-field copy of instances of that class.
  4. Serializable - An interface that allows it's implementers to be serialized and deserialized.
public class ArrayList extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable

Here's the inheritance hierarchy for an ArrayList:


java.lang.Object
   ↳    java.util.AbstractCollection<E>
       ↳    java.util.AbstractList<E>
           ↳    java.util.ArrayList<E>

3 ways of Instantiating an ArrayList

The ArrayList class provides us three constructors that allow us instantiate an ArrayList:

  1. ArrayList() - Constructs an empty list with an initial capacity of ten. This is the most commonly used in many examples.

Here's one:

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

Find complete android example here.

  1. ArrayList(int initialCapacity) - Constructs an empty list with the specified initial capacity.

  2. ArrayList(Collection<? extends E> c) - Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

4 ways of Adding Data to an ArrayList.

The essence of having a data structure like an a arraylist is for it to hold some lists of data. Those data have to be added.

Defined in the AbstractList which is the parent of the ArrayList class are a couple of add methods which we can use depending on our requirements.

  1. boolean add(E element) - You pass an element as a parameter and it gets appended to the end of the list.

For example let's say we have an arraylist named languages which should us programming languages:

        languages.add("Java");
        languages.add("C#");
        languages.add("VB.NET");
        languages.add("PHP");

In the above case we are adding String objects. Find complete android example here.

However we can also add custom objects. Assuming we have an ArrayList named people to hold a list of human being names:

            Person p=new Person(); 
            p.setName("Mike"); 
            people.add(p.getName()); 
            p=new Person(); 
            p.setName("John"); 
            people.add(p.getName()); 

Find full example here

  1. void add(int index, E element) - Inserts the specified element at the specified position in this list.

  2. boolean addAll(Collection<? extends E> c) - Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator.
private ArrayList<Song> getSongList(@NonNull List<Playlist> playlists) {
    final ArrayList<Song> songs = new ArrayList<>();
    for (Playlist playlist : playlists) {
        if (playlist instanceof AbsCustomPlaylist) {
            songs.addAll(((AbsCustomPlaylist) playlist).getSongs(activity));
        } else {
            songs.addAll(PlaylistSongLoader.getPlaylistSongList(activity, playlist.id));
        }
    }
    return songs;
}

Here's another example:

public static void main(String[] args) {

        ArrayList<Integer> al = new ArrayList<Integer>();

        for(int i=0; i<5f; i++) {
            al.add(i);
        }
        al.forEach(p -> { System.out.print(p+","); });
        System.out.println();

        al.addAll(al);
        al.forEach(p -> { System.out.print(p+","); });

}
  1. boolean addAll(int index, Collection<? extends E> c) - Inserts all of the elements in the specified collection into this list, starting at the specified position.

Sorting an ArrayList

Here's an example:

private void sortPresentations() {
    final ArrayList<Component> sortedComponentList = new ArrayList<>();
    componentPresentationMap.keySet().forEach(sortedComponentList::add);
    sortedComponentList.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));
    sortedComponentList.forEach(component -> componentPresentationMap.get(component).toFront());
}

Top ArrayList Quick Example Snippets

(a). How to Populate an ArrayList from Database

First we create a PreparedStatement with our SQL select statement:

        PreparedStatement ps = connection.prepareStatement("select * from lab");

Then invoke the executeQuery() method of the prepareStatement class, thus returing us a result set which we hold in a ResultSet object.

        ResultSet rs = ps.executeQuery();

Then we instantiate our ArrayList to hold our data. Then loop through the ResultSet using a while loop and the next() method, filling our ArrayList and returning it outside our loop.

public ArrayList<Lab> getLab() {
    try {
        PreparedStatement ps = connection.prepareStatement("select * from lab");
        ResultSet rs = ps.executeQuery();
        ArrayList<Lab> labs = new ArrayList<Lab>();
        while (rs.next()) {
            Lab lab = new Lab(rs.getInt("labId"), rs.getString("labName"), rs.getString("testFor"),rs.getString("labResult"),
                    rs.getString("reportFile"),rs.getInt("itemId"),getDoctor(rs.getInt("doctorId")));
            labs.add(lab);
        }
        return labs;
    } catch (SQLException e) {
        e.printStackTrace();
        return null;
    }
}
(b). How to Sort an ArrayList and ListView using Comparator in Java

Let's assume we have a User object.

public class User
{
    private String name;
    private Float score;

    public User(String name,Float score)
    {
        this.name = name;
        this.score = score;
    }

    public String getName()
    {
        return this.name;
    }

    public Float getScore()
    {
        return this.score;
    }
    @Override
    public String toString()
    {
        return this.name + ": " + Float.toString(this.score) + " wpm";
    }
}

And want to sort our ArrayList of users. Each as you can see from the above has a name and a score, which is a Floating Point number.

Now we want to sort those users according to their scores and show the result in a ListView in android.

Then our activity will be like this. Needless to say you need to specify imports and create a layout for your project.

public class Highscores_Standard extends AppCompatActivity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        setTitle(Game.TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_highscores__standard);

        ArrayList<String> userNames = Game.readFile(Highscores_Standard.this,Game.USERSFILENAME);
        ArrayList<String> userScores = Game.readFile(Highscores_Standard.this,Game.SCORESFILENAME);

        ArrayList<User> users = new ArrayList<User>();

        for (int x = 0; x < userNames.size(); x++)
        {
            users.add(new User(userNames.get(x),Float.parseFloat(userScores.get(x))));
        }

        users.sort(Comparator.comparing(User::getScore));
        Collections.reverse(users);

        ListView listView = (ListView) findViewById(R.id.listBox);
        ArrayAdapter<User> arrayAdapter = new ArrayAdapter<User>(this,android.R.layout.simple_list_item_1,users);
        listView.setAdapter(arrayAdapter);

    }
}

In the above we are assuming that we are reading the usernames and their game scores from the filesystem into our arraylist. You may just use dummy data or fetch data from database.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post