How to code Java #6 – Arrays and ArrayLists


Back in Part 2, we looked at how we can store values in our programs by replacing them with symbols called ‘variables’. Variables are brilliant, but the trouble is they only store one value at a time. What if you want to store ten values? Or a hundred? Having to code up 100 variables to store 100 values would make for messy code in no time flat and keeping track of them would be nightmare! But as you’d expect, there’s a simpler way, using a data structure called an ‘array’.

vararrayIndexed variables

An array is a collection of what are called an ‘indexed variables’. So far, we give a variable a name or ‘symbol’ and we store one value in it. If we make that variable an array instead, we create a number of same-type variables that can be accessed by the one symbol and an index. Clear as mud?

Let’s try an analogy – if you live in an apartment block, you don’t just live in the apartment block, but in a separate apartment, which has its own number. The block has its own address and each apartment is referenced or ‘indexed’ by the apartment number. You may live in unit 1, the noisy guy playing the Van Halen solos in unit 5. Arrays are a similar concept.

To use an array, first, you must declare it by coding its data type and name, then initialise its values. For example, we could declare an array of card suites like this:

String[] cardSuites = new String[4];

We tell Java to create a new String array with four elements (new String[4]) and assign it (=) to a new String array (String[]) variable called ‘cardSuites’. We can now add data to each element in the array like this:

cardSuites[0] = “hearts”;

cardSuites[1] = “diamonds”;

cardSuites[2] = “clubs”;

cardSuites[3] = “spades”;

A couple of things to notice here – first, the use of square brackets [] rather than curly ones to indicate the index; and second, the index always starts from zero.

App #1 – Resistor Colour Code Calc

ccOkay, enough theory – let’s do something with it. One of the first things you learn when studying electronics is the resistor colour code. After a while, you learn it by heart and it makes identifying resistor values as easy as looking at the colour bands.

But when you’re just starting out, it can be confusing and easy to make mistakes. That’s where a simple app can make things easier. We’ll solve this techie problem using an array.

First up, you can see the how the resistor colour code works in the chart. The resistor shown has five coloured bands – the first three indicate the first three digits of the resistor value, the fourth the ‘multiplier’, the fifth, the ‘tolerance’. Many resistors have just four colour bands with the third digit band missing.

In the case of the resistor shown, we get the colours brown, black, black, red, brown reading from the end the bands are closer to. Using the code chart, we have ‘100’ as the first three digits, a ‘x100’ multiplier and a ‘+/-1% tolerance’. To work out the resistor value, we get 100 x 100, or 10,000-ohms (10kΩ) and the tolerance means the value must be between 9900 and 10100-ohms.

Stick to the code!

ccodeNow let’s look at our Java code. After we declare the class ‘ColourCode’, you’ll see that we declare and initialise a String array called digitColour. The difference here is we’re using a common shortcut known as an ‘array initialiser’. Remember before how we declared the array first and initialised it in separate code-lines? The array initialiser allows you to do it all in the one line:

static String[] digitColour = {"black","brown","red","orange","yellow","green","blue","purple","grey","white"};

This is a string array called digitColour and each indexed variable is filled in turn with one of the comma-separated strings between the curly braces on the right of the equals (=) sign. What you get is digitColour[0] gets assigned ‘black’, digitColour[1] ‘brown’ and so on down to digitColour[9] as ‘white’.

Next, we now launch into the app using the main method and ask the user to enter in a resistor value between 10 and 10million ohms. We also introduce a second method called getColour that has an integer parameter called ohms.

Look at the last codeline of the main method – it’s a basic ‘println’ statement but right at the end, we’re pausing the main method to start or ‘call’ the getColour method and sending it the value in the ‘ohms’ integer variable, the number typed in by the user previously.

Here in this new method, we first initialise a string variable call code, then we get the first two digits of the number the user typed in and store them into integer variables digit1 and digit2. The two codelines that obtain these values look completely different but they actually deliver the same result – we’re just showing you two different ways to get there.

The first turns the integer value of ohms into a string, grabs the first character as a sub-string and converts that back into an integer. The second turns the ‘ohm’ integer value into a string, but this time, grabs the second character (index ‘1’) as a ‘char’ type value and converts it into the literal numeric value. In most coding tasks, there is almost always more than one way to do something.

Once we have those two single digits, we convert them into a three-digit value by multiplying the first by 100, the second by 10 and storing the result in integer variable threeDigits.

resoutWhy do this? Resistor values are set using a number sequence of ‘preferred values’ known as an E-series with E12 and E24 series the most common. E12 values are 10, 12, 15, 18, 22, 27, 33, 39, 47, 56, 68, 82 – and they are multiplied by factors of 10 to get set values between 1.0-ohms and 10-megaohms. Bottom-line, E12 and E24 preferred values are always two-digits – that mean the third digit in commonly-found resistors is always zero. By multiplying the two-digit value by 10, we get the value of the first three.

Now to get that fourth ‘multiplier’ digit, if we divide the total resistor value by the value of the first three digits, we get the multiplier factor, but we really need the multiplier factor as a factor of 10 – in other words, the mathematical log to base-10. And we get that using Java’s Math.log10 function and store the result in the integer variable multiplier. Here’s how it works – if we divide the resistor value (10000 in our example) by the first three digits (100), we get 100. The base-10 log of that is two (you just count the number of zeros). And from the code, we know two is red. If we were working with four-ring resistors, the final ‘times-10’ on that the codeline would be removed.

Finally, we now get to use the digitColour array. We use the digit1 and digit2 values as indexes to the array to recall the correct colours and likewise use the multiplier variable as index for the correct multiplier colour. These colours are written to a string called code, which is returned to the main method, the code string is printed to the screen and the app finishes.

Variable arrays – ArrayLists

arraylistArrays are brilliant if you know the size you need initially, but what if you don’t? How do you change the size of an array in your code on-the-run or ‘dynamically’? That’s easy – you don’t. Once an array is declared, its size is fixed – you cannot change it. If you want a variable-sized array, what you actually want is what’s called an ‘ArrayList’. Now we’re getting dangerously close to some advanced topics such as object-oriented programming, collections and data structures, but even at this early stage it’s worth just a brief toe-dipping into these waters.

An ArrayList is an extendable array of data ‘objects’. Objects are a huge area we’ll cover in later guides, but essentially in Java, you can create an array list of almost anything once you define what that something is. The difference between an array and an ArrayList is that with ArrayLists, you can add to them, you can delete and insert elements and have the other elements move up or shuffle down automatically as appropriate. One example of how you can use ArrayLists is when creating a list of customers – you can add new ones, insert or delete others. You can also search and sort ArrayLists, but that’s for another time.

App #2 – ArrayList demo

arcodeRather than leave you scratching your head over all of this, we’ve deliberately kept our second app nice and simple, so you get a feel for how ArrayLists work. We start by creating an ArrayList of strings called words. Prior to Java 7, this line would’ve needed to have been:

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

But Java 7 brought in the shortcut we’ve used in our code:

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

Next, we ask the user to type in a sentence, which is then stored in String variable sentence. We then take that variable and use a String class method called split, which allows you to split a string into an array of strings based on one or more delimiter characters. We can do this simply by using spaces as the delimiter so that we end up with a string array of words called wordList1 with each word now an element in that array.

This works well, but remember, now that we’ve created the array, we can’t add to it, nor can we remove any element – we can delete an element’s contents but not the element itself, so the elements following won’t move up. So instead, we now take each element of the wordList1 array and add it to the words ArrayList using the one-line addAll method. First, we convert the wordList1 array into a list using the Arrays.asList function, then add each element to the words ArrayList via addAll.

Now that we have the sentence as an array list of strings, we can remove and insert at will. Next in our code, we delete/remove the second word in the list – remember, array/list indexes start from zero, so the second word is at index 1. We use the remove command to remove the element at index 1 and the rest automatically move up.

After that, we ask the user for a replacement word, store it in string variable newWord and use that word to plug back into word ArrayList at index 1. We do that with the add method again but this time, we include the index position we want the word to go into as an extra parameter and the name of the string referencing the word.

Finally, we ask the user for a second sentence and using the ‘add’ method, again add in each word from the new sentence to the end of the words ArrayList.

Basic keys to using arrays

arrayoutThere are a few key things to remember when using arrays or ArrayLists – first is how to retrieve the size. You’ll find this important to know in most apps, even in our demo here. To find the size of an array, you need the array.length function, but for an ArrayList, you need ArrayList.size() method. Something to remember.

Another key feature is whenever you access an array or ArrayList, the index must be within the array size/length, otherwise, you’ll get a run-time error.

And finally, you’ll notice that to obtain the value of a particular element of an array, you use array[index] whereas in an ArrayList, you use ArrayList.get(index).

Lots more

Lists are just one example of Java’s data structure or ‘collections’. Throw in stacks (simple list where last-in is first-out), queues (first-in is first-out) and sets (no duplicates are stored) and there are many ways you can manipulate data in Java.

Next time

The first six parts of this series have been all about filling your toolbox with the basics nuts and bolts of simple Java coding. Using the console to get input and display output has made that nice and easy. But starting next time, we crank things up a gear and begin looking at how to build Windows-like graphical user interface or GUI apps, with panels, buttons, radio buttons and all the rest. See you then.

  • Lyn Taylor

    Could not find the previous part #5 on ‘Methods’