alice in action with java chapter 12 arrays and lists in java

Post on 22-Dec-2015

233 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Alice in Action with Java

Chapter 12Arrays and Lists in Java

Alice in Action with Java 2

Objectives

• Understand Java’s array data structure

• Solve problems using Java’s LinkedList data structure

• Solve problems using Java’s ArrayList data structure

Alice in Action with Java 3

Arrays and Lists in Java

• Features common to arrays and lists– Used to define variables that store groups of items– Provide access to a given item using an index

• Differences between arrays and lists– Array’s size is fixed at runtime, a list’s size can change– Array stores items using less memory than a list– Array provides direct item access faster than a list

Alice in Action with Java 4

Introductory Example: Air Pollution Reporting

• Review of AirPollutionIndex.java– Read air pollution level readings from five points– Compute and display the average reading (the index)

• Additional requirements of the enhanced program– Display the five readings used to compute the average

• High-level algorithm for AirPollutionReport– Build an array named readings with length = 5 – Read the air pollution readings into readings– Compute and display average of values in readings– Display the individual values in readings

Alice in Action with Java 5

Java Arrays

• General pattern for defining (declaring) an array– Item[] anArray = new Item[N];

• Item: specifies the items type

• Brackets tell compiler that anArray is an array handle• new operator: allocates memory for the array• N: an integer that specifies the array length (size)

• An example of an array definition: double[] readings = new double [NUM_READINGS];– NUM_READINGS is an integer constant = 5– readings is a handle to a 5 unit double type array

Alice in Action with Java 6

Java Arrays (continued)

• Element: indexed unit variable in an array

• Item: value stored in an array element

• Items are initialized to default values for array’s type– Example: default value for item in double type is 0.0

• Creating an array parameter– Place brackets between parameter’s type and its name– General form: public ReturnType methodName( Item[] parameterName ){…

– Example: public static double average(double [] anArray)

Alice in Action with Java 7

Java Arrays (continued)

Alice in Action with Java 8

Java Arrays (continued)

• Components needed to access an array’s elements– Array’s handle, item’s index, subscript operator ([])

• Pattern for accessing an element: anArray[i]– anArray is the handle to the array – i: index value, which must be a non-negative integer– An index value out of bounds throws an exception

• Example of an array access: readings[0]– Accesses the first element of the readings array– Note: index is off by one relative to item’s cardinal order

• length property: returns number of items in an array

Alice in Action with Java 9

Java Arrays (continued)

• for loop provides convenient access to an array

• Example of an array traversal using a for loop– for (int i = 0; i < arr.length; i++){

System.out.println("Reading #" + (i+1) + ": " + arr[i]);}

• for each loop – Special loop used to read each item in an array– Limitation: cannot be used to write to array’s elements

• Example of array traversal using a for each loop– for (double item : anArray){sum += item;}

Alice in Action with Java 10

Example 2: Month Names From Numbers

• Essential elements of user story – Randomly generate a month number– Query user for a month name matching the number– Read the user’s response– Display a message appropriate to the response– Let the user keep playing as long as he or she wants

• Instance variables declared in the Month class– An integer myNumber and a string myName

• Role of the Month()constructor– Construct a Month object given a month number

Alice in Action with Java 11

Example 2: Month Names From Numbers (continued)

• MONTHS will be used to store the month names– The array is declared as a constant class variable– Declaration also includes an initialization values list– The array functions as a lookup table for the constructor

• Other Month members– Accessors for the instance variables– A toString()method

• Other classes used in MonthTester– Random (to generate a random number)– Scanner (to read in the month’s name)

Alice in Action with Java 12

Example 2: Month Names From Numbers (continued)

Alice in Action with Java 13

Arrays and Memory

• An array is a random access data structure– Contiguous elements are accessed in constant time

• Subscript operation computes an element’s address

• How to compute the address of an array element– Multiply the index i by the size of an item– Add the resulting product to the starting address– Example: anArray[4]= (anArray+4*itemSize)

• Insertion and removal are linear time operations– Up to length–1 items are shifted in each operation– Many of these operations can slow down a program

Alice in Action with Java 14

Arrays and Memory (continued)

Alice in Action with Java 15

Arrays and Memory (continued)

Alice in Action with Java 16

Multidimensional Arrays

• Dimension: axis used to specify element’s location • length determines space for one-dimensional array

• You can create arrays with multiple dimensions– Example: two-dimensional array to model a table

• How to declare an N-dimensional array handle– Use N pairs of brackets to declare

• Example of declaring a two-dimensional array– private double [][] myTable = null;

Alice in Action with Java 17

Multidimensional Arrays (continued)

• Defining a multidimensional array with default values – Use the new operator and specify dimensions– Ex: myTable = new double[rows][columns];

• Defining multidimensional array with non-default values– Use an initialization list

• Accessing a multidimensional array element– Use N subscript operators for N dimensions– Example: myTable[row][col] = item;

• Processing multidimensional arrays – Use N for loops to traverse array with N dimensions

Alice in Action with Java 18

Lists in Java

• Interface: a structure that only declares methods

• A class implementing an interface defines methods

• Example: String implements CharSequence• Java’s List is an interface

• Two classes implementing List– LinkedList: similar to Alice’s list data structure– ArrayList: dynamic container offering fast access

Alice in Action with Java 19

Lists in Java (continued)

Alice in Action with Java 20

Lists in Java (continued)

Alice in Action with Java 21

Using ArrayLists

• ArrayList implements the List interface• Features of an ArrayList

– Reference type data structure– Can increase in size during execution– set()and get()access items in constant time

• Patterns for declaring and defining an ArrayList

• Insert items in an ArrayList using add()

Alice in Action with Java 22

Using ArrayLists

• Rules for declaring an array list– The type of an array list must be a reference type– Use a wrapper class when a primitive type is needed

• Wrapper class contains primitive type plus operations

• Pattern for declaring an ArrayList– ArrayList<ItemType> handleName = null;

• Example of a ArrayList declaration– ArrayList<Double> listOfNumbers = null;

• Produces a handle called listOfNumbers• listOfNumbers is capable of storing an arbitrary

number of Double objects

Alice in Action with Java 23

Using ArrayLists (continued)

Alice in Action with Java 24

Using ArrayLists (continued)

Alice in Action with Java 25

Summary

• Array: fixed-size container used to store items of the same type

• Items: values stored in an array’s elements

• Accessing an array element is a constant time operation

• Inserting and removing items in an array are linear time operations

• Arrays can have an arbitrary number of dimensions• ArrayList includes the random access capability of

arrays and the ability to change size

top related