The Word of the Day is List!

I am still working on a post about the Bartenderbot project (gonna be a big post) so in the meantime, I’d like to talk to you about Lists.

Quick background for the non-programmer audience, bear with me programmers.
There are many ways of storing data in computer science. These ways of storing are called “Data Structures”. They range from stacks and heaps to arrays and lists. The ones I will be discussing today in the most detail are arrays and lists. Arrays are ordered lists, almost like a row of numbered boxes each holding some data. This allows data to be accessed according to its position in the array. Arrays are notated with square brackets and indexed by an integer in those brackets.

int[] arr;
int x = arr[i];

Because of their ability to store and load data quickly, arrays are quite common, and my code used to be full of them. That is until I discovered the full potential of lists.

Arrays have a fatal flaw. When an array is made, it has a set length. That is to say if you want to add data to a full array, you need to create a new longer array, copy all the old data in to the new array, then add the new data. Lists avoid this flaw.

List is actually a misnomer. Java.Util.List is an abstract class, meaning it cannot be instantiated. Rather, you must used a class that inherits List. My favorite such class is Java.Util.ArrayList. ArrayLists use the afforementioned arrays as backing structures, but takes care of all the messy array reassignment internally. So if you have a full ArrayList, and you want to add one more object, you only need to call list.add(object); and the list will append the new object.

My past week has been centered around finishing the software for the Bartenderbot. This software relies on collections of Ingredients, Instructions and Recipes, which I had previously set up as arrays of the corresponding objects. After writing:

Instruction[] temp = new Instruction[instructions.length+1];
for(int i=0; i<instructions.length; i++){
    temp[i] = instructions[i];
}
temp[temp.length-1]=newGuy;
instructions = temp;

for the nth time, I tried switching to lists.

After reassigning variables throughout the code, it was amazing how many lines I saved. I turned for loops into foreach loops, arr[i]’s into .get(i)’s, and the previously shown add functions into .add()’s. So if you haven’t already, go make some lists and correct the overuse of arrays.

Leave a comment