AP Computer Science A -- Unit 5

An array is a simple but powerful way to group and organize data. When we have a large amount of information, such as list of 100 names, it is not practical to declare separate variables for each of data. Arrays solve this problem by letting us declare one variable that can hold many values.


Arrays | Arrays of Objects | Two-Dimensional Arrays | The ArrayList Class | Review


Arrays

an array example

An array in Java is a complex data structure because it can store a list of primitives or objects. It also stores them in such a way that each of item in the list can be referenced by an index.

Array declarations look like this:

array example

type[] arrayName;

This tells the compiler that arrayName contains a reference to an array containing type. However, the actual array object is not constructed by this declaration. The declaration merely declares a reference variable arrayName which, sometime in the future, is expected to refer to an array object.

Often an array is declared and constructed in one statement, like this:

type[] arrayName = new type[ length ];

This statement does two things:

  1. It tells the compiler that arrayName will refer to an array containing cells of type.
  2. It constructs an array object containing length number of cells.

Length Field

After an array is created and initialized, you can ask it how many slots it has by using the length field. Think of the length as an instance variable for an array. The length field is not a method and does not have a part of parenthesis at the end. The length field of an array returns the total number of slots that are set aside for that array. It does not return the total number of valid elements in that array. Also, since the first index of any array is always zero, the length of the array is always one more the last index.

Example:

Find the length of the foodChoices array:

int result = foodChoices.length;

Assignment: Arrays Worksheet

Directions: Complete the multiple choice Arrays worksheet in itsLearning. You should trace through the problems to determine the correct answer. Code tracing is important and will help you be successful on the AP Exam.

Fibonacci

Lab: Reversing an Array

Directions: Write a program that prompts the user for an integer, then asks the user to enter that many values. Store these values in an array and print the array. Then reverse the array elements so that the first element becomes the last element, the second element becomes the second to last element, and so on, with the old last element now first. Do not just reverse the order in which they are printed; actually change the way they are stored in the array. Do not create a second array; just rearrange the elements within the array you have. (Hint: Swap elements that need to change places.) When the elements have been reversed, print the array again.

Follow your teacher's instructions for submitting the code of the lab as well as a screenshot from BlueJ.

Need help? Watch this video for the concept of reversing an array (note: the code in the video is not Java).


Arrays of Objects

Arrays can store references to objects. Fairly complication information management structures can be created using only arrays and other objects. When we store objects in an array, each element is a separate object (actually it is an array of object references.)


Two-Dimensional Arrays

Two-dimensional arrays allow us to store data in a matrix or grid format, instead of the data just being linear as with arrays or ArrayLists. A two-dimentional (2-D) array is a complex data structure that can be visualized as a rectangular grid made up of rows and oclumns. Technically, it is an array of arrays. It can store any kind of data in its slots; however, each piece of data has to be the same data type.

A 2-D array object can be created using the keyword new. Every cell in the 2-D array is filled with the default value for its data type.

General Form for creating a 2-D Array Using the Keyword new

dataType[][] nameOfArray = new dataType[numberOfRows] [numberOfColumns];

Traversing a 2-D Array in Row-Major Order

Traversing a 2-D array means to visit each and every cell in the grid. This can be done in many different ways, but for the AP Exam, you need to know two specific ways:

Assignment: Secret Code

Directions: Download the SecretCode file and print it. You will need to fill in the 2D array in row-major (meaning rows come first) order and then decode the secret code. There is what appears to be a typo but it leave it. You'll know it when you get to it. Follow your teacher's instructions for submitting your Secret Code assignment.

Assignment: Array Free Response

Directions: Download the Array Free Response file and print it. Follow the instructions and complete the code. The code must be handwritten. Follow your teacher's instructions for submitting the assignment.

magic

Lab: Magic Squares

Directions: Download the Magic Squares lab. One interesting application of two-dimensional arrays is magic squares. A magic square is a square matrix in which the sum of every row, every column, and both diagonals is the same. Magic squares have been studied for many years, and there are some particularly famous magic squares. In this exercise you will write code to determine whether a square is magic.

File Square.java contains the shell for a class that represents a square matrix. It contains headers for a constructor that gives the size of the square and methods to read values into the square, print the square, find the sum of a given row, find the sum of a given column, find the sum of the main (or other) diagonal, and determine whether the square is magic. The read method is given for you; you will need to write the others. Note that the read method takes a Scanner object as a parameter.

File SquareTest.java contains the shell for a program that reads input for squares from a file named magicData and tells whether each is a magic square. Following the comments, fill in the remaining code. Note that the main method reads the size of a square, then after constructing the square of that size, it calls the readSquare method to read the square in. The readSquare method must be sent the Scanner object as a parameter.

You should find that the first, second, and third squares in the input are magic, and that the rest (fourth through seventh) are not. Note that the -1 at the bottom tells the test program to stop reading.

Follow your teacher's instructions for submitting the code of the lab as well as a screenshot from BlueJ.


The ArrayList Class

An ArrayList is very similar to an array, however, it can only collect object unlike arrays that can also hold primitive data. They can grow or shrink as needed. ArrayLists also come with methods for many useful tasks.

ArrayList Methods

Assignment: ArrayList Worksheet

Directions: Complete the multiple choice ArrayList worksheet in itsLearning. You should trace through the problems to determine the correct answer. Code tracing is important and will help you be successful on the AP Exam.

shopping cart

Lab: A Shopping Cart Using the ArrayList Class

Directions: Download the A Shopping Cart Using the ArrayList Class lab. In this exercise you will implement a shopping cart using the ArrayList class. The file Item.java contains the definition of a class named Item that models an item one would purchase. An item has a name, price, and quantity (the quantity purchased). The file Shop.java is an incomplete program that models shopping.

Follow your teacher's instructions for submitting the code of the lab as well as a screenshot from BlueJ.

Assignment: ArrayList Free Response

Directions: Download the ArrayList Free Response document. Read the comments for the instructions and complete the ArrayList methods. Your code must be handwritten to receive credit. Follow your teacher's instructions for submitting the code.


Assignment: Unit 5 Review Worksheet

Directions: Complete the review worksheet in itsLearning to review for the unit assessment.

Assignment: Array Free Response Exercise

Directions: Download Array Free Response document and handwrite the code following the detailed instructions. You must also read the code comments provided for you as they give valuable information and instructions to help you write the class and methods required.

Review

Credits

Array Example Image: http://www.mainjava.com/java/core-java/complete-array-tutorial-in-java-with-programming-example/