Skip to main content

Programming Fundamentals: 6.1 How Does This Topic Relate to Object Oriented Programming?

Programming Fundamentals

6.1 How Does This Topic Relate to Object Oriented Programming?

6. Arrays and ArrayLists

6.1. How Does This Topic Relate to Object Oriented Programming?

Arrays and ArrayLists both play an important part in the Object Oriented programming landscape. For both structures, classes with utility methods exist for performing common operations such as sorting and searching. ArrayLists are defined as first class OO objects, with attributes and methods which describe the contents, characteristics and functions of this important class. In a short amount of time, you will frequently be integrating ArrayLists and OO programs in a seamless and very natural manner!

6.2. Learning Objectives

  • Learn about a fundamental data structure in programming - the Array
  • Learn how to declare, initialize, access and modify arrays
  • learn how to process elements in an array through iteration
  • Introduce the array’s object-oriented construct, the ArrayList
  • Learn how to declare, initialize, access and modify ArrayLists
  • Understand the tradeoffs of using arrays and ArrayLists
  • Learn about advanced capabilities of ArrayLists: such as: adding sublists, removing sublists, search ArrayLists

6.3. Key Terms

Review the important terms in Chapter 8.11 and Chapter 12.11 of ThinkJava.

6.4. Resources

6.4.1. Text

  • Think Java Chapter 8 - Arrays
  • Think Java Chapter 12 - Arrays of Objects

6.4.2. Video / Tutorial

  • Core Java 11 Fundamentals, Second Edition LiveLesson (requires login)
    • Arrays
    • ArrayList Intro Part 1 Part 2 Part 3

6.5. Overview

Until now, we have dealt with variables that deal primarily with a single value. In many programs, it is helpful to treat similar items as a group. The java programming language provides mechanisms to refer to a group with one variable: arrays and ArrayLists.

Why two? That would take a longer explanation, but we can simplify for now by saying that arrays are more efficient and should be used when efficiency is paramount; ArrayLists are less efficient and as a result easier to program and more flexible.

Some languages allow programmers to mix data types within an array structure. In general, and although it is possible, such mixing is strongly discouraged when programming in Java.

6.6. Arrays

6.6.1. Creating Arrays

6.6.2. JavaTutor Example

Java Tutor example

6.6.3. Indexing Arrays

The index of each value in a list describes its location in the list. Indexes start with the first value at position 0 and end with the last value at position length - 1. The indexes for the list ["Apple", "Plumb", "Kiwi"] are below. Note that the list is of length 3 and thus has indexes from 0 to 2.

Table 7. Indexing

List Values"Apple" "Banana" "Cherry"
Indexes012

6.6.4. JavaTutor Example

Java Tutor example

Note that since we can access and modify elements in a list, we can also swap them. Can you figure out how to swap the first and last elements of any list?

6.6.5. Array Properties

6.6.6. JavaTutor Example

Java Tutor example

6.6.7. Arrays and For Loops

In Java, programmers can process a series of steps multiple times, by looping. Arrays and loops go together well, since it is often desirable to perform some processing on each element in an array. The following examples illustrate looping, first with Java’s enhanced for loop and then with an indexed for loop.

6.6.8. JavaTutor Example

Java Tutor example

6.6.9. JavaTutor Example

Java Tutor example

6.6.10. Arrays Example

Let’s roll two fair, six sided die 5 times and store the results in an array. Additionally, we will tally the number of occurrences of each roll total and print these out with a crude bar chart.

6.6.11. JavaTutor Example

Java Tutor example

6.7. ArrayLists

As mentioned earlier, ArrayLists are similar to Arrays in their functionality. Also noted previously, ArrayLists are not as efficient as arrays, but are much more flexible.

6.7.1. Creating ArrayLists

6.7.2. JavaTutor Example

Java Tutor example

An astute observer will recognize several subtle nuances in the above code. First, the storage size does not need to be declared at the outset, as with arrays. Next, even though it appears that odds will contain primitive ints, these are wrapped in objects of type Integer.

The observer will also see that several shorthand notation conventions are employed when creating the evens ArrayList. The Integer parameterized type can be omitted on the right-hand side of the equal sign, whenever the type can be inferred. The literal values (2,4,6) can added to the array directly, taking advantage of a Java technique known as autoboxing. (Autoboxing converts a primitive to the corresponding wrapper class, when inference is possible. Autounboxing works the same, when conversions are needed in the opposite direction).

In the case of the special ArrayList, this code demonstrates that the handling of double (/Double wrapper class) works similar to the Integer examples which proceeded it. Finally, Since Integer, Double and String are all Java classes, ArrayLists operate similarly for the fruits Collection. The similarities extend beyond String too, and will apply to any Java Class!

It is possible to rewrite the code:

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

to

ArrayList odds = new ArrayList();

However, this is strongly discouraged. This allowance is made to permit older code to run against newer versions of the Java Virtual Machine (JVM), without modification. The guidance to avoid using this shorthand is provided since coding errors can pass through at compile/build time but will be exposed at a later date, when it is more difficult and costly to correct the issue.

6.7.3. Indexing ArrayLists

Like with arrays, the index of each value in a list describes its location in the list. Indexes start with the first value at position 0 and end with the last value at position length - 1. The indexes for the fruits list are below. Note that the list is of length 3 and thus has indexes from 0 to 2.

Table 8. Indexing

List Values"Apple" "Banana" "Cherry"
Indexes012

6.7.4. JavaTutor Example

Java Tutor example

6.7.5. ArrayList Maintenance - Adding and Removing Elements

6.7.6. JavaTutor Example

Java Tutor example

6.7.7. ArrayList Methods

ArrayLists have many convenience methods. Popular methods include length(), contains(), indexOf() and clear() and trimTo(). Documentation for these and others can be found at the Java website.

Additional methods shuffle() and sort() from the Collections class will also work with ArrayLists.

The following example illustrates the use several ArrayList and Collections methods.

6.7.8. JavaTutor Example

Java Tutor example

6.7.9. ArrayLists and For Loops

ArrayList traversal is conducted similar to that of array processing. ArrayList values can be visited with a traditional or enhanced for loop syntax.

6.7.10. JavaTutor Example

Java Tutor example

6.7.11. Dice Rolling Example, Revisited

6.7.12. JavaTutor Example

Java Tutor example

6.7.13. ArrayList to Array Conversion, and Vice-Versa

Sometimes, we will need to convert an array to san ArrayList or vice-versa. The syntax to go back and forth is not very symmetric, since and ArrayList is an object while an array is not. The following code example demonstrates one way to transition back and forth.

6.7.14. JavaTutor Example

Java Tutor example

It is important to realize that array < - > ArrayList conversions can be resource-intensive for larger data sets.

6.8. Exercises

6.8.1. Exercise 1

Create an integer array named dice1 with a size of 10. Populate each array location with a roll of a six-sided die (hint: an int value of 1 through 6). Print the array out using an enhanced for loop.

Sample output:

dice1 = 1 1 6 2 3 5 1 5 4 5

6.8.2. Exercise 2

Create an integer array named dice2 with a size of 6. Populate each array location with a roll of a six-sided die (hint: an int value of 1 through 6). Print the array out using an indexed for loop.

Sample output:

dice2 = 4 5 6 1 4 1

6.8.3. Exercise 3

Create an ArrayList of Integers named dice3. Generate an Integer representing a roll of a six-sided die 10 times, adding each result to dice3. (hint: generate a random integer value between 1 and 6, inclusive). Print the ArrayList using an enhanced for loop.

Sample output:

dice3 = 3 5 5 1 2 5 3 2 6 5

6.8.4. Exercise 4

Create an ArrayList of Integers named dice4. Generate an Integer representing a roll of a six-sided die 5 times, adding each result to dice4. (hint: generate a random integer value between 1 and 6, inclusive). Print the ArrayList using an enhanced for loop.

Sample output:

dice4 = 3 2 4 4 1

6.8.5. Exercise 5

Consider the following source:

int[] list1 = {1, 2, 3, 4, 5, 6, 6, 6, 7,  8, 8, 8, 9, 10};
int[] list2 = {2, 4, 8, 10, 12, 14, 16,  18, 20};

Create an new ArrayList named intersection that contains only those items that occur in both lists. If a value is duplicated in either list and it occurs in both lists, it should only occur once in the intersection list. For the lists provided, your ArrayList should contain: 2 4 8 10

6.8.6. Exercise 6

Consider the follow ArrayList:

ArrayList<LocalDate> centennials =  new ArrayList<>();
centennials.add(LocalDate.of(1776,  Month.JULY, 4));
centennials.add(LocalDate.of(1876,  Month.JULY, 4));
centennials.add(LocalDate.of(1900,  Month.JULY, 4));
centennials.add(LocalDate.of(1976,  Month.JULY, 4));
centennials.add(LocalDate.of(2076,  Month.JULY, 4));

As you can observe, a java programmer has mistakenly entered the 1900
date item into the ArrayList. Without removing the associated
centennials.add(...) source line, write the code to remove the errant
entry. Print out the resulting ArrayList and size as follows:

Before removal:

07/04/1776
07/04/1876
07/04/1900
07/04/1976
07/04/2076
size = 5

After removal:

07/04/1776
07/04/1876
07/04/1976
07/04/2076
size = 4

Hint: you should use the DateTimeFormatter class for formatting.

6.8.7. Exercise 7

Consider the following ArrayList:

ArrayList<LocalDate> centennials =  new ArrayList<>();
centennials.add(LocalDate.of(1776,  Month.JULY, 4));
centennials.add(LocalDate.of(1876, Month.JULY,  4));
centennials.add(LocalDate.of(1976,  Month.JULY, 4));
centennials.add(LocalDate.of(2076,  Month.JULY, 4));

write the code necessary to determine the ArrayList size.

Sample output:

size = 4

6.8.8. Exercise 8

Consider the follow ArrayList:

ArrayList<LocalDate> centennials =  new ArrayList<>();
centennials.add(LocalDate.of(1776,  Month.JULY, 4));
centennials.add(LocalDate.of(1876,  Month.JULY, 4));
centennials.add(LocalDate.of(1976,  Month.JULY, 4));
centennials.add(LocalDate.of(2076,  Month.JULY, 4));

write the code necessary to determine if the centennial (1876, at 100 years) is present.

Sample output:

centennial present = true

6.9. Do You Have Any Questions about Chapter 6?

Comments

Next Chapter
7.1 Learning Objectives
PreviousNext
This text is licensed under a CC BY 4.0 license.
Powered by Manifold Scholarship. Learn more at manifoldapp.org