a rrays in j ava : t he b asics section 6.0 ap computer science

82
ARRAYS IN JAVA: THE BASICS Section 6.0 AP Computer Science

Upload: samantha-poole

Post on 24-Dec-2015

216 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

ARRAYS IN JAVA: THE BASICSSection 6.0

AP Computer Science

Page 2: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

ARRAY STORAGE

Recall that arrays have two main parts: A name, which is used to reference the array An index value (also called subscript) that is

used to access specific values in the array.

grades

Array index values ALWAYS begin at zero!Largest index value in an array is size - 1

78 82 91 65 77

0 1 2 3 4

Page 3: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

USING INDEX VALUES

To access individual values in an array, the name of the array is used with the index value inside of brackets. The brackets used with an array are treated as an operator with the highest precedence!

distance[10] = 27.25;speed = distance[i] / 5; System.out.println(“Distance = “ + distance[0]);

Because index values are integers, the value in the brackets MUST evaluate to an integer.

Page 4: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

DECLARING ARRAYS

In Java, arrays are objects! Variables are object reference variables! Array must be instantiated!

Syntax of Array Declaration:type[ ] name = new type[size];

type = Data type for array name = Name of array size = # of items in the array

Page 5: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

EXAMPLES OF ARRAY DECLARATIONS

int[] numbers = new int[10]; //10 slot array

int size = 20;double[] taxRates = new double[size]; //20 slots!

char [] colors;colors = new char[256]; //256 slot array

Page 6: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

DECLARING ARRAYS

The data type for an array can be any primitive data type OR any object type (class).

All values stored in the array will have the same data type cannot mix and match!

Once the size of an array is declared, it cannot be changed.

Page 7: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

BOUNDS CHECKING WITH ARRAYS

When an array location is accessed, the operator performs bounds checking making sure the provided index value is valid for the array. Index value MUST be in the range of 0 to (size – 1).

If the provided index value is invalid, Java will throw a ArrayIndexOutOfBoundsException.

Off-by-one Error Common error where the programmer “forgets” that each location is “off by one” (ex. the first location has an index of zero, NOT one)

Page 8: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

OBTAINING THE LENGTH OF AN ARRAY

The length of an array can be quickly identified using the length constant available to all array objects. arrayName.length No parentheses!!!

The length constant is declared AFTER the array is instantiated.

Page 9: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

INITIALIZER LISTS An initializer list is a list of values for an array that is

provided at the array’s initialization. The use of an initializer list is limited to when the array is declared.

To create an initializer list: Separate each item with a comma (,)

Each item MUST be of the same data type Enclose the list within braces Use the list in place of the new operator

The size of the array will become the # of items in the initializer list

Ex: int[] foodCost = {6.99, 7.25, 8.35, 6.50, 5.25};String[] names = {“Joe”, “Jack”, “Jane”, “Jenny”};

Page 10: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

ARRAYS AND LOOPS

Due to the fixed size of an array, a for loop can be used to quickly work through and/or process the data contained in an array.

Specifically… Printing all of the values in an array Adding all of the values in an array Obtaining values for each “cell” in an array

Page 11: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

EXAMPLE: OBTAINING VALUES

int[] nums = new int[10];Scanner scan = new Scanner(System.in);

for(int i = 0; i < nums.length; i++){

System.out.print(“Enter integer value: “);nums[i] = scan.nextInt();

}

Page 12: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

EXAMPLE: FINDING THE TOTALdouble[] values = {13.45, 16.67, 18.91, 22.35, 4.51, 8.26};double total = 0;

for(int count = 0; count < values.length; count++){

total += values[count];}

System.out.println(“The total of all values is “ + total);

Page 13: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

ARRAYS AND METHODS

Arrays can be used as parameters for class methods!

When writing a parameter list for a method, the parameter for the array will require the data type of the array, a set of brackets, and a parameter name. Ex: public int getTotal(int[] numbers)

Because an array is an object, any changes done to the array inside a method are PERMANENT!!!

Page 14: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

ARRAYS OF OBJECTSSection 6.1

AP Computer Science

Page 15: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

CREATING ARRAYS OF OBJECTS

Like primitive data types, arrays can be created that are filled with objects of a specific class.

Declaring an array of objects is identical to declaring an array of primitive data:

type [] arrayName = new type[size]; The data type, in this case, is the name of the

class being used.

Page 16: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

EXAMPLE – CREATING OBJECT ARRAYS

String [] cityList = new String[10];//Creates an array of 10 String objects

Student[] classList = new Student[28];//Creates an array of 28 Student objects

Animal [] zoo;zoo = new Animal[30];//Creates an array of 30 Animal objects

Page 17: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

WHY MAKE ARRAYS OF OBJECTS?

Can eliminate the need for parallel arrays (two or more arrays linked by their index values)

Useful for programs that contain a large number of similar objects. Example: Consider a program that manages a

roster of players for a football team.

Page 18: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

ARRAYS OF OBJECTS & INSTANTIATION

An array of objects will hold a memory address in each slot. These memory addresses are the link to the stored objects.

Upon creation, each slot in the array is empty (null). Each object in the array MUST be instantiated by using a constructor method for each object.

Page 19: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

SEARCHING ARRAYS

AP Computer Science

Section 6.2

Page 20: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

HOW CAN SEARCH AN ARRAY FOR A VALUE?

2 4 7 11 14 15 23

Page 21: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

LINEAR / SEQUENTIAL SEARCH

Algorithm Start at beginning of array Compare contents of first index to target

If value is found, stop loop Move to next index value. Repeat until value is

found.

Advantages Can be used with any array Easiest to implement

Disadvantage Very slow when working with large amounts of data

Page 22: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

BINARY SEARCH

Algorithm: Pre-sort array from low to high / high to low Find middle of array and compare to target.

Consider only values in possible half of array Find middle of this “half” and compare to target

Continue in this manner until value is found/not found

Advantage Faster than Linear Search

Eliminate half of the possibilities each step of the way

Disadvantage Requires array to be sorted before the search.

Page 23: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

BINARY SEARCH

2 4 7 11 14 15 23

2 4 7 11 14 15 23

2 4 7 11 14 15 23

Find 14… Start Here

Since 14 > 11, move to 2nd half

Since 14 < 15, move below

Page 24: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

COMPARING VALUES

For primitive values (int, double, char, etc.), you can use normal equality and comparison operators.

For Strings… Use the .equals method to test for equality.

Returns true or false if(string1.equals(string2))

Use the .compareTo method to compare strings Returns 0 if equal, negative if s1 < s2, positive if s1 >

s2 if(string1.compareTo(string2) > 0)

Page 25: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

WHEN TO USE EACH SEARCH METHOD

Use a linear search when… Amount of data to search is fairly small Data is not sorted Efficiency is not an issue

Use a binary search when… Amount of data to search is large Data is pre-sorted

Page 26: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

SORTING ALGORITHMSSection 6.3

AP Computer Science

Page 27: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

ESSENTIAL QUESTIONS

What is a selection sort?

What is a bubble sort?

What is an insertion sort?

Page 28: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

SORTING

The process of rearranging the elements in an array in a specific order (lowest to highest or highest to lowest).

For now, we will learn about the… Selection Sort Bubble Sort Insertion Sort

Page 29: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

SELECTION SORT A selection sort is sorting algorithm where,

one slot at a time, each value is placed in its proper location.

Starting at the first position in the array, the array is searched for the largest/smallest value. When it is found, the values are swapped.

At the next slot, the “rest” of the array is searched until the next largest/smallest value is found. These values are swapped.

This repeats until the end of the array.

Page 30: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

SELECTION SORT - ALGORITHM

For each position in the array{

Find smallest/largest value from current position to end of the array.

Swap value in current position with found value.

}

Page 31: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

SELECTION SORT

3 9 6 1 8 2 5

1 9 6 3 8 2 5

1 2 6 3 8 9 5

Start Here – Scan for smallest & swap

Scan from here

1 2 3 6 8 9 5

1 2 3 5 8 9 6

Page 32: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

BUBBLE SORT

A bubble sort is a sorting method where adjacent values are compared and rearranged in the array until all are sorted.

This is called a “bubble” sort because the smaller values “float” to the top.

Page 33: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

BUBBLE SORT - ALGORITHM

while #passes < size and numbers swapped{

increase #passes by 1for each index - #passes

compare two adjacent valuesif 2nd value greater than 1st, swap

}

Page 34: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

BUBBLE SORT – PASS #1

3 6 1 8 2 5 9

3 9 6 1 8 2 5

3 9 6 1 8 2 5

3 6 9 1 8 2 5

3 6 1 9 8 2 5

3 6 1 8 9 2 5

3 6 1 8 2 9 5

Page 35: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

BUBBLE SORT – PASS #2

3 1 6 2 5 8 9

3 6 1 8 2 5 9

3 6 1 8 2 5 9

3 1 6 8 2 5 9

3 1 6 8 2 5 9

3 1 6 2 8 5 9

3 1 6 2 5 8 9

Page 36: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

BUBBLE SORT – PASS #3

1 3 2 5 6 8 9

3 1 6 2 5 8 9

1 3 6 2 5 8 9

1 3 6 2 5 8 9

1 3 2 6 5 8 9

1 3 2 5 6 8 9

1 3 2 5 6 8 9

Page 37: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

INSERTION SORT

An insertion sort is similar to sorting a hand of cards.

In an insertion sort, each value is looked at and placed in its appropriate location in a “sorted” list.

Page 38: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

INSERTION SORT - ALGORITHM

for each value in the array starting at 1{

Get value and index of current positionSearch “sorted” part of array for fitPlace value in new location

}

Page 39: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

INSERTION SORT

1 2 3 6 8 9 5

1 2 3 6 8 5 9

3 9 6 1 8 2 5

3 9 6 1 8 2 5

3 9 6 1 8 2 5

3 6 9 1 8 2 5

1 3 6 9 8 2 5

1 3 6 8 9 2 5

Page 40: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

COMPARING SORTSSection 6.4

Page 41: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

EFFICIENCY Algorithm Efficiency – used to judge

algorithms based on speed and/or data.

Time Efficiency The time required for an algorithm to run completely.

Space Efficiency The amount of space (memory) an algorithm requires.

Using less space and/or completing in a faster time = more efficient algorithm

Page 42: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

MEASURING EFFICIENCY

Time efficiency measured by how many statements get executed. More statements = larger time requirement

How does the running time grow as the size of the array grows?

Page 43: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

SELECTION SORTfor(int i = 0; i < array.length; i++){

for(int s = i + 1; s < array.length; s++){//Statements inside}

}

If n is the number of items in the array, then the outer loop will run n times, while the inner loop will run from 1 – n times, depending on the outer loop.

Thus, its efficiency is n * n = n2

Page 44: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

BIG – OH NOTATION

In Computer Science, big-oh notation is used to identify the time efficiency of an algorithm.

The selection sort has an efficiency of O(n2), which means that, as a worst case scenario, the algorithm will run on the order of n2 units of time.

Page 45: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

INSERTION SORT

An insertion sort is ALSO a nested loop that run n times each, so the insertion sort also has an efficiency of O(n2).

Page 46: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

BIG-O METHODS Common magnitudes of big-O notation are

(from least complex to most complex):

O(1) Constant O(log n) Logarithmic O(n) Linear O(n log n) n log n O(n2) Quadratic O(n3) Cubic O(2n) Exponential

Page 47: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

O(1)

An O(1) algorithm is one which has a constant execution time, regardless of size.

Ex: public int sum(int[] a){

return a[0] + a[a.length – 1];}

Page 48: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

O(N) An O(n) algorithm varies directly with the size of the

input data set. Single Loop Structure

Ex:public int search(int[] a, int searchVal){

for(int i = 0; i < a.length; i++)if(a[i] == searchVal)

return i;return -1;

}

Page 49: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

ANOTHER O(N) EXAMPLE

int sum(int [] a, int i){

if (i > a.length)return 0;

elsereturn a[i] + sum(a, i+1);

}

Page 50: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

O(N2) An O(n2) algorithm varies directly with the square of the size of the

data set. Common for programs with nested loops Additional nesting will result in O(n3), O(n4)

Ex: void bubbleSort(int[] a){

int k = 0; while(k < a.length() – 1){

k++;for(int j = 0; j < a.length() – k; j++)

if(a[j] < a[j + 1])swap(a, j, j+1);

}}

Page 51: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

O(LOG N)

An O(log n) method will increase rapidly at the beginning, but will eventually level off in terms of a time requirement as the data set increases.

Ex: Binary Search Size of searched array continually is cut in half

Page 52: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

HOW BIG-O VALUES VARY If n = 1

O(1) = 1 O(n) = 1 O(log n) = 0 O(n2) = 1

If n = 10 O(1) = 1 O(n) = 10 O(log n) = 1 O(n2) = 100

Page 53: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

SPACE EFFICIENCY Space efficiency can also be measured using

big-oh notation.

In most sorting arrays, the amount of memory used is a number of memory locations equal to the array’s length.

Selection and Insertion sorts have efficiency levels of O(n).

Page 54: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

WHAT DOES IT ALL MEAN?

Time efficiency is gained by limiting the number of lines of code the algorithm must process.

Sequential and Insertion Sorts have a time efficiency of O(n2) and a space efficiency of O(n).

Neither sort method has any real efficiency advantage over the other.

Page 55: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

TWO – DIMENSIONAL ARRAYSSection 6.6

Page 56: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

TWO DIMENSIONAL ARRAYS

Two Dimensional Arrays – an array that has values in “two – dimensions”. Typically imagined as “rows and columns”.

When using two-dimensional arrays, the reference requires two index values. The first index value is the “row” The second index value is the “column”

Page 57: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

DECLARING TWO DIMENSIONAL ARRAYStype [] [] name = new type[#rows][#columns];

int [ ] [ ] values = new int [3][5]; Creates an array with 3 rows and 5 columns

double [ ] [ ] earnings = new double[5][5]; Creates an array with 5 rows and 5 columns

Monster [] [] house = new Monster[2][2]; Creates an array with 2 rows and 2 columns

Page 58: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

INITIALIZING A 2D ARRAY

2D arrays can be initialized using an initializer list. However, each row must be contained in its own set of curly braces.

int[ ] [ ] ratings = { {5, 7, 8}, {2, 3, 4}}

This would be a 2 x 3 array 5 7 8 2 3 4

Page 59: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

USING TWO-DIMENSIONAL ARRAYS

The index value of the first cell in the row AND column is zero.

To access/change the value of a cell, use the following: name[row][column] = value or expression;variable = name[row][column];

Page 60: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

EXAMPLE

char[ ][ ] a = new char[3][4];

a[0][0] a[0][1] a[0][2] a[0][3]

a[1][0] a[1][1] a[1][2] a[1][3]

a[2][0] a[2][1] a[2][2] a[2][3]

Page 61: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

EXAMPLE

char[ ][ ] a = new char[3][4];

‘a’ ‘b’ ‘c’ ‘d’

‘e’ ‘f’ ‘g’ ‘h’

‘i’ ‘j’ ‘k’ ‘L’

Page 62: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

LENGTH OF TWO-DIMENSIONAL ARRAY

The length constant for a two dimensional array object CAN be used to quickly find the dimensions of the array, with the following considerations;

int [][] example = new int[5][3]; example.length Returns # of rows example[row].length Return # of columns

Page 63: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

LOOPS AND TWO-DIMENSIONAL ARRAYS Two dimensional arrays can be manipulated

easily by using a nested for loop.

Typically, the outer for loop will keep track of the rows, while the inner loop will keep track of the columns.

for(int r = 0; r < array.length; r++)for(int c = 0; c < array[r].length; c++)

//Process elements

Page 64: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

THE ARRAYLIST CLASSSection 6.7

Page 65: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

THE ARRAYLIST CLASS

java.util.ArrayList

An arrayList object works just like a standard array. However…Does not need to be declared to store a

particular data type. (Stores list of references to the Object class)

Items can be added to or removed from the list at any point in time. This will cause the size to change.

This class is part of the Collections API

Page 66: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

CREATING AN ARRAYLIST

To create an arrayList in a program, you need to…. import the appropriate library

import java.util.ArrayList; construct the arrayList

ArrayList variable = new ArrayList();

Page 67: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

ARRAYLIST CLASS METHODS

boolean add (Object obj)Adds the object to the end of the ArrayList

void add (int index, Object obj)Adds the given object into the ArrayList at

the given position

Object set(int index, Object obj)Replaces the element at index with the

provided object, and returns the replaced object.

Page 68: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

ARRAYLIST CLASS METHODS

Object get(int index) Returns the object at the given index.

Object remove(int index) Removes the object at the index from this list

and returns it.

int size() Returns the number of elements in the list

Page 69: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

ARRAYLIST CLASS METHODS

void clear() Removes all elements from the list

boolean contains(Object obj) Returns true if the object is found in the list

int indexOf(Object obj) Returns the index of the first occurrence of the

object OR -1 if the object is not found.

Page 70: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

WHAT CAN BE STORED IN ARRAYLISTS? ArrayLists can be used to store any object

An arrayList will store a list of references to the “Object” class (more on this later)

Primitive data can be stored in an arrayList by storing it in a Wrapper class.

Page 71: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

WRAPPER CLASSES

A wrapper class is a class that is used to create an object that holds primitive data as an object. It “wraps” data into an object!

Wrapper classes exist for all primitive data types!

Page 72: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

THE INTEGER WRAPPER CLASS

Integer(int value) Constructor creates new Integer object that

represents the value provided.

int compareTo(Object other) Returns a number indicating whether the integer

is less than (a negative return value), greater than (a positive return value), or equal (a zero return value) to the integer other.

Page 73: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

THE INTEGER WRAPPER CLASS

boolean equals(Object other)Returns true if this integer has the same

value as the integer other.

int intValue()Returns the value of this object as an int.This “unwraps” the integer!

String toString()Returns a String object representing this

integer’s value.

Page 74: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

EXAMPLE OF WRAPPING/UNWRAPPINGInteger num = new Integer(10);//num is now an Integer object that contains

the value 10.

int value = num.intValue();//value is now 10!

Page 75: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

THE DOUBLE WRAPPER CLASS

Double(double value)

int compareTo(Object other)

double doubleValue()

boolean equals(Object other)

String toString()

The constructor and methods work in a similar way to the constructor and methods from the Integer class.

Page 76: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

AUTOBOXING

Autoboxing is the automatic conversion between a primitive value and its appropriate wrapper object.

Integer numObject;int num1 = 22;numObject = num1; //Wraps

int num2 = numObject; //Unwraps

Page 77: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

BACK TO ARRAYLISTS – ADDING/REMOVING Any time an object is added/removed

from an arrayList, the size changes automatically!!!

ArrayList class = new ArrayList();class.add(“Joe”); [“Joe”]class.add(“Megan”); [“Joe”, “Megan”]class.add(“Carol”); [“Joe”, “Megan”, “Carol”]class.remove(“Joe”); [“Megan”, “Carol”]

Page 78: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

ARRAY LISTS OF OBJECTS

Because an arrayList holds references to the base Object type, it can contain any object.

To receive a specific object from an arrayList, the returned object needs to either…Be cast as the objectBe obtained from an arrayList that has a

specified type.

Page 79: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

OPTION 1: CASTING OBJECTS You can cast objects as specific types in a

similar way to casting data as primitive types.

Ex: (className)variable Ex: (className)variable.method()

t = (Toy)aList.get(0);

Page 80: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

OPTION 2: SPECIFY TYPE OF LIST

An arrayList can be created to hold objects of a specific type.

ArrayList <className> variable = new ArrayList <className>();

Ex: ArrayList<Student> sList = new ArrayList<Student>();

Page 81: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

ARRAYLISTS AND EFFICIENCY

When items are added/removed from the end of an ArrayList, efficiency is NOT affected. Don’t need to waste time/space moving

items around.

When items are added/removed from the front of a long ArrayList, efficiency decreases due to the need to copy/move items.

Page 82: A RRAYS IN J AVA : T HE B ASICS Section 6.0 AP Computer Science

EXAMPLE: SHUFFLED DECK

Use the Card class to create a deck of cards in an ArrayList.

“Shuffle” the deck and print the cards out one at a time, including the number left in the deck.