0% found this document useful (0 votes)
10 views89 pages

Lecture04 2025 Array ArrayList

This lecture covers the differences between Arrays and ArrayLists in Java, including their initialization, accessing elements, and passing them as arguments to methods. It explains the concepts of primitive types versus objects, reference semantics, and how to manipulate arrays of objects. Additionally, it addresses common errors and provides examples of using arrays in methods and algorithms.

Uploaded by

kjpassakorn1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views89 pages

Lecture04 2025 Array ArrayList

This lecture covers the differences between Arrays and ArrayLists in Java, including their initialization, accessing elements, and passing them as arguments to methods. It explains the concepts of primitive types versus objects, reference semantics, and how to manipulate arrays of objects. Additionally, it addresses common errors and provides examples of using arrays in methods and algorithms.

Uploaded by

kjpassakorn1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

LECTURE 04

Array and ArrayList


ITCS123 Object Oriented Programming
Dr. Aniqua Nusrat Zereen
Dr. Petch Sajjacholapunt
Dr. Pisit Praiwattana

Semester 2/2025 27 January 2026


Recap – Lecture 03
Object & Class
Implementing Class
Instance variables (or instance fields or attributes)
Different Kinds of Methods in a class
Constructor
Accessor Method (e.g., getter)
Mutator Method (e.g., setter)
Static Methods
Encapsulation and scope of variables
Access specifiers: public, protected, default, private

2
Outcomes of this lecture
Can explain the different between Array vs ArrayList
Can demonstrate how to construct and initialize both Array and ArrayList
Can demonstrate how to store primitive data type variables and reference data
type variables in Array and ArrayList
Can implement a program to access and change values or elements in both
Array and ArrayList
Can implement a program to pass Array as arguments to methods
Can use Array, ArrayList, and 2 dimensional arrays (2D Arrays) to implement
basic algorithms

3
Array
Introduction to Array
Initializing Array of Primitive Type
Initializing Array of Objects
Accessing Array of Primitive Type and Objects
Passing Array as Arguments to Methods

4
Recall: Primitives vs. objects
In java, a variable can be either
Primitive
Has well-defined set of possible values
Primitive types are lowercase and shown as keyword in Eclipse.
E.g. int, double, char, boolean
Reference
Similar to C/C++, You can think of it as a pointer to an object.
An object is a class instance or an array.
Yes, an array is an object!

User Defined

5
Introduction to Array
Array: a container of values/objects of the same data type
e.g., shopping cart contains value of items, waiting queue contains value of person, etc.
After creation its length is fixed
Variable declared as an array is object reference

6
Syntax – Construct & Declaration
A "name tag" (reference variable) is created on the Stack. It currently holds null (it points
to nothing = null).
arrayOfString
null
(ref)

arrayOfChars
null
(ref)

isActive null
(ref)

nationalDebt
null
(ref)

arrayOfInts
null
(ref)

Stack
7
Syntax – Construct & Declaration
The new keyword carves out actual space on the Heap. This is the
physical "object." arrayOfString arrayOfString
(ref) Object
The "name tag" on the Stack is updated to point to the memory
address of the object on the Heap.
arrayOfChars arrayOfChars
(ref) Object

isActive isActive
(ref) Object
array_type [ ] array_name = new array_type [sizeOf theArray ];

int [ ] arrayOfInts = new int [10]; //array of int primitives nationalDebt nationalDebt
long [ ] nationalDebt = new long [10]; //array of long primitives (ref) Object
boolean [ ] isActive = new boolean [1]; //array of bollean primitives
char [ ] arrayOfChar = new char [5]; // array of cchar primitives
String [ ] arrayOfString = new String [2]; //array of String Objects
arrayOfInts arrayOfInts
(ref) Object

Stack Heap
7
Syntax – Construct & Declaration
array_type [ ] array_name = new array_type [sizeOf theArray ]; BankAccount BankAccount
(ref) Object

arrayOfString arrayOfString
(ref) Object
int [ ] arrayOfInts = new int [10]; //array of int primitives
long [ ] nationalDebt = new long [10]; //array of long primitives
boolean [ ] isActive = new boolean [1]; //array of bollean primitives
char [ ] arrayOfChar = new char [5]; // array of cchar primitives arrayOfChars arrayOfChars
String [ ] arrayOfString = new String [2]; //array of String Objects (ref) Object
BankAccount [ ] accounts = new BankAccout [10]; //array of user defined Object
isActive isActive
(ref) Object

nationalDebt nationalDebt
(ref) Object

arrayOfInts arrayOfInts
(ref) Object

Stack Heap
7
Arrays of Objects
BankAccount Class contains information such as accountNumber and balance

public class BankAccount {


private int accountNumber;
private double balance;
// . . . acc1
0
}

in main method we can create an array of BankAccount Objects


we can create BankAccount Objects and store inside the array

// accounts array

BankAccount[] accounts = new BankAccount[10];

// BankAccouunt Object

BankAccount acc1 = new BankAccount();

accounts[0] = acc1;
9
Initializing Array of Objects
// BankAccouunt Object instead of creating
different variables
BankAccount[] accounts = new BankAccount[5]; (acc1), we can
BankAccount acc1 = new BankAccount();
for (int i = 0; i < [Link]; i++) directly create the
accounts[0] = acc1; object inside the
accounts[i] = new BankAccount(); array index

accountNumber = 0
The accounts variable balance = 0.00
holds the address of an address
BankAccount array.
accountNumber = 0
accounts[0] address
null balance = 0.00

accounts[1] address
null
accountNumber = 0
accounts[2] address
null balance = 0.00
accounts[3] address
null
accountNumber = 0
accounts[4] address
null
balance = 0.00

The array is an array of references


(addresses) to BankAccount objects accountNumber = 0
balance = 0.00 11
Accessing Array Elements
Use [ ] to access an element
Assigning values 0.0
data[2] = 29.95; 0.0

accounts[7] = new BankAccount(1021); 0.0


0.0
Using the value stored: 0.0
0.0
double d = data [4]; 0.0
0.0
BankAccount ba = accounts[7]; 0.0
[Link]("The value of this data item is " + data[4]);
[Link]("The balance of this account is " + accounts[7].getBalance());

accounts[7] holds an object

12
Array Size
To get array size When array is created without defining values, all values
are initialized to the default values depending on the
//Syntax array's data type:
[Link] Numbers: 0 (for int) or 0.0 (for double)
// Example Boolean: false
[Link] Object References: null
[Link]
// Example
int nums = new int[5];
(length is a property of an array. [Link](nums[3]); // 0
It is NOT a method!)

Tip! Instead of using a number as a size declarator, it is common practice to use a 'final' variable.

final int ARRAY_SIZE = 10;


int[] numbers = new int[ARRAY_SIZE];
13
Common Errors: Accessing Array Elements
Accessing a nonexistent element results in a bounds error
Index values range from 0 to length – 1
int [] data = new int [8];
data[8] = 29; // 'Run-time ERROR'
// [Link]: 10

Accessing uninitialized Arrays


double[] data;
data[0] = 29.95; // 'Compile-time ERROR'
// The array variable:data is declared, but not initialized

14
Summary: Primitive Type VS Objects
int[] numbers = new int[6];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40; address 10 20 30 40 50 60
numbers[4] = 50;
numbers[5] = 60;

int[] numbers = {10,20,30,40,50,60};

String[] names = new String[4];


names[0] = "Bill";
names[1] = "Susan";
names[2] = "Steven";
names[3] = "Jean";

String[] names = {"Bill", "Susan", "Steven", "Jean"};

15
Self Check
What elements does the data array contain after the following statements?

double[] data = new double[5];


for (int i = 0; i < [Link]; i++) {
data[i] = i * i;
}

Answer: 0, 1, 4, 9, 16,
a) 0 0 0 0 0
but not 25!b)
Which choice is the correct answer 0 1 4 9 16
c) 0 1 4 9 16 25
d) 1 4 9 16 25
16
Self Check
What do the following program segments print? Matching the results with the provided code.

[Link][] a = new double[10]; 1.a run-time error:


[Link](a[0]); array index out of bounds
[Link][] b = new double[10];
2.a compile-time error:
[Link](b[10]);
array is not initialized
[Link][] c;
[Link](c[0]); 3.0.0

17
Array in Methods
Does the following swap method work? Why or why not?
public static void main(String[] args) {
int a = 7;
int b = 35;
// swap a with b?
swap(a, b);
[Link](a + " " + b); ////OUTPUT
7 35 ??
}
public static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}

18
Primitive: Value semantic
value semantics: Behavior where values are copied when assigned, passed as
parameters, or returned.

All primitive types in Java use value semantics.


When one variable is assigned to another, its value is copied.
Modifying the value of one variable does not affect others.

int x = 5;
int y = x; // x = 5, y = 5
y = 17; // x = 5, y = 17
x = 8; // x = 8, y = 17

19
Primitive Types Variable as Parameter
When you pass a variable of primitive type as an argument to a
method, the method gets a copy of value stored in the variable.
Any modification made to the variable will not be visible to the caller
public void increaseNum(int n) {
n++;
}

int n = 5;
increaeseNum(n);
[Link](n); // OUTPUT?

20
Object: Reference semantic
Reference semantics: Behavior where variables actually store the
address of an object in memory.

When one variable is assigned to another, the object is not copied;


both variables refer to the same object.
Modifying the value of one variable will affect others. BE CAREFUL!!!
Array variable is an object variable, so it behaves the same way.

int[] a1 = {4, 15, 8}; index 0 1 2


int[] a2 = a1; // refer to same array as a1 a1
a2[0] = 7;
[Link](a1[0]); // 7 value 74 15 8

a2
21
Why Reference Semantic?
Arrays and objects use reference semantics.
efficiency. Copying large objects slows down a program.
sharing. It's useful to share an object's data among methods.

Panel p1 = new Panel(80, 50);


Panel p2 = p1; // same window
[Link]([Link]);

p1
Note that Panel is a user-defined
p2 class

22
Objects as parameters
When an object is passed as a parameter, the object is not copied.
The parameter refers to the same object.
If the parameter is modified, it will affect the original object.

public static void main(String[] args) {


Panel window = new Panel(80, 50);
[Link]([Link]);
example(window);
}
window
public static void example(Panel panel) {
[Link]([Link]);
...
}

panel

23
public class BankAccount {
public int accountNumber; Account Number
public double balance; Balance

public BankAccount(int accNum, double balance){


[Link] = accNum;
[Link] = balance;
}
OUTPUT
public void change(int num){
[Link]("Inside increase"); Inside increase
num = 888
// change value of primitive type
num = 888; BankAccount = 999.0
[Link]("num = " + num); Inside main
// change value of reference type amount = 10
[Link] = 999;
[Link]("BankAccount = " + [Link]);
BankAccount = 999.0
}

public static void main(String[] args){


BankAccount myAccount = new BankAccount(1, 100); No.1, $100
int amount = 10;
Primitive type – method gets a
[Link](amount); copy of value
//[Link](amount, myAccount);
[Link]("Inside main"); Object type – method gets the
[Link]("amount = " + amount); object’s reference
[Link]("BankAccount = " + [Link]);
}
}
Passing Array vs Element
Suppose you have an array of primitive type (int)
int[] num = new int[10];
sortArray(num); // call method
To pass an array as an argument to the method, the array's reference is passed so the corresponding parameter
in the method header must be of array type as well. For example,
public void sortArray(int[] x){ … }
To pass an individual element of an array to the method, the corresponding parameter in the called method
header must be the same type of the element.

int[] num = new int[10]; Car[] carList = new Car[10];


... ...
increaseNum(num[2]); setColor(carList[2]);

public void increaseNum(int x){ public void setColor (Car x){


x++ [Link] = "Red"
} } 26
Passing Element as Arguments to Methods
// Create an array.
int[] numbers = {5, 10, 15, 20, 25, 30, 35, 40};

// Pass each element to the ShowValue method.


for (int index = 0; index < [Link]; index++)
showValue(numbers[index]);

/**
* The showValue method displays its argument. */
public static void showValue(int n) {
[Link](n + " ");
}

Program Output:

5 10 15 20 25 30 35 40
27
Passing Array as Arguments to Methods
public static void main(String[] args){
// Create an array.
int[] numbers = {5, 10, 15, 20, 25, 30, 35, 40};

// Pass the array to the showArray method.


showArray(numbers);

// Pass the array to the increaseArray.


increaseArrayValues(numbers);
[Link]("\nValues inside main");
for (int value : numbers) {
[Link](value + " ");
}
}
Values inside showArray
5 10 15 20 25 30 35 40
Values inside main
6 11 16 21 26 31 36 41

/** /**
* The showArray method accepts an array as * The increaseArrayValues method accepts an array as
* an argument displays its contents. * an argument and increase value of each element by one.
*/ */
public static void showArray(int[] array) { public static void increaseArrayValues(int[] array){
// Display the array elements. for (int i = 0; i < [Link]; i++){
[Link]("Values inside showArray"); array[i] += 1;
for (int i = 0; i < [Link]; i++) }
[Link](array[i] + " "); }
}
28
Simple Array Algorithms
Enhanced for Loop
Find Minimum, Maximum, and Average
Compare Arrays
Copy Array
Insert and Delete Element to and from Array at specific index
Resize Array

29
The Generalized for Loop
Traverses all elements of a collection:
double[] data = . . .; Read this loop as
double sum = 0; "for each e in data"
for (double e : data) {
sum = sum + e;
}

In each iteration, the variable ‘e’ is assigned the next element of the collection.
Then the statement ‘sum = sum + e’ is executed.

Traditional alternative:
double[] data = . . .;
double sum = 0;
for (int i = 0; i < [Link]; i++)
{
double e = data[i];
sum = sum + e;
} 30
Self Check
Write a "for each" loop that prints all elements in the array data.
Answer:
for (double x : data)
[Link](x);

Why is the "for each" loop not an appropriate shortcut for the
following ordinary for loop?

for (int i = 0; i < [Link]; i++)


data[i] = i * i;
Answer: The loop writes a value into data[i]. The "for
each" loop does not have the index variable i.
31
Self Check
Write a "for each" loop that prints all elements in the array data.
Answer:
for (double x : data)
[Link](x);

Why is the "for each" loop not an appropriate shortcut for the
following ordinary for loop?

for (int i = 0; i < [Link]; i++)


data[i] = i * i;
Answer: The loop writes a value into data[i]. The "for
each" loop does not have the index variable i.
31
Find Min, Max, Average
final int ARRAY_SIZE = 50;
int[] numbers = new int[ARRAY_SIZE];

int highest = numbers[0];


for (int index = 1; index < [Link]; index++) {
if (numbers[index] > highest)
highest = numbers[index];
}

int lowest = numbers[0];


for (int index = 1; index < [Link]; index++) {
if (numbers[index] < lowest)
lowest = numbers[index];
}

double total = 0;
for (int index = 1; index < [Link]; index++) {
total += numbers[index];
}
double average = total/[Link];
32
Compare Arrays
int[] firstArray = { 5, 10, 15, 20, 25 };
int[] secondArray = { 5, 10, 15, 20, 25 };
if (firstArray == secondArray) // This is a mistake. Why?
[Link]("The arrays are the same.");
else
[Link]("The arrays are not the same.");

boolean arraysEqual = true; // Flag variable


int index = 0; // Loop control variable

// First determine whether the arrays are the same size.


if ([Link] != [Link])
arraysEqual = false;

// Next determine whether the elements contain the same data.


while (arraysEqual && index < [Link]){
if (firstArray[index] != secondArray[index])
arraysEqual = false;
else
index++;
}
if (arraysEqual)
[Link]("The arrays are equal.");
else
[Link]("The arrays are not equal.");
33
Copy Arrays: Copy Array References
Copying an array variable yields a second reference to the same array

double[] data = new double[10];


// fill array . . .
double[] prices = data;

34
Copy Arrays: Clone Arrays
Use clone to make true copy (Return from a method clone is an "Object" type.
double[] prices = (double[]) [Link](); clone method returns Object type

Don’t forget to cast

35
Copy Array Elements
[Link]:
Copies an array from the specified source array, beginning at the specified position, to the specified position
of the destination array.

Parameters: [Link](src, srcPos, dest, destPos, length);


src the source array.
double[] test double[] copy
srcPos starting position in the source array.
dest the destination array.
1.0 0.0
destPos starting position in the destination data.
length=3
length the number of array elements to be copied. 2.5 1.0
9.9 2.5
2.2 9.9
Output
double[] test = {1.0, 2.5, 9.9, 2.2}; 0.0
double[] copy = new double[5]; 0.0
[Link](test, 0, copy, 1, 3); 1.0
for(double x: copy){ 2.5 what if src and dest array are the same?
[Link](x); 9.9
} 0.0
36
Insert an Element to an Array
[Link](src, srcPos, dest, destPos, length);

First move all elements from i onward one position up


[Link](data, i, data, i + 1, [Link] - i - 1);
Then insert the new value
data[i] = x;

The last element


in the array is lost

37
Delete an Element from an Array
[Link](src, srcPos, dest, destPos, length);

[Link](data, i + 1, data, i, [Link] – i - 1);

Last element will be copied twice!


38
Resize an Array
If the array is full and you need more
space, you can resize the array:

Create a new, larger array:


double[] newData = new double[2 * [Link]];
Copy all elements into the new array:
[Link](data, 0, newData, 0, [Link]);
Store the reference to the new array in the array variable:
data = newData;

You may assign newData = null if you dont want to keep a copy and release memory allocation

39
Self Check
How do you add or remove elements in the middle of an array list?
Answer: Use the insert and remove methods.

Why do we double the length of the array when it has run out of space
rather than increasing it by one element?
Answer: Allocating a new array and copying the elements is
time-consuming. You wouldn't want to go through the process
every time you add an element.

40
Two Dimensional Arrays
Construct and Initialize 2D Arrays
Traverse 2D Arrays
length field in 2D Arrays
Sum Values in 2DArrays
Three or More Dimensional Arrays
Tic-Tac-Toe Board Game

41
Construct and Initialize 2D Arrays
To construct two-dimensional array,
we need to know how many rows and columns are required:

double[][] scores = new double[3][4];

99

Access elements with an index pair variable_name[i][j]


scores[2][1] = 99;

42
Initialize a 2D Array
int[][] numbers = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
visualization

int[][] numbers = { {1, 2, 3},


{4, 5, 6},
{7, 8, 9} };

43
Example: A Tic-Tac-Toe Board
Full source code for Tic-TacT-oe board game application:
including class TicTacToe ([Link]) and class
TicTacToeRunner ([Link]) can be found in
final int ROWS = 3; Appendix A at the end of this presentation
final int COLUMNS = 3;
String[][] board = new String[ROWS][COLUMNS];

board[1][1] = "X";
board[2][1] = "O";

44
Traverse Two-Dimensional Arrays
It is common to use two nested loops when filling or searching:

for (int i = 0; i < ROWS; i++)


for (int j = 0; j < COLUMNS; j++)
board[i][j] = " ";

45
Traverse Two-Dimensional Arrays
prompts the user to enter a score, once for each element in the scores array.
final int ROWS = 3;
final int COLS = 4;
double[][] scores = new double[ROWS][COLS];
double number;
Scanner keyboard = new Scanner([Link]);
for (int row = 0; row < ROWS; row++){
for (int col = 0; col < COLS; col++) {
[Link]("Enter a score: ");
number = [Link]();
scores[row][col] = number;
}
}

displays all the elements in the scores array.


for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
[Link](scores[row][col]);
}
} 46
length field in 2D Array
int[][] numbers = { { 1, 2, 3, 4 },{ 5, 6, 7, 8 }, { 9, 10, 11, 12 } };

// Display the number of rows.


[Link]("The number of rows is " + [Link]);

// Display the number of columns in each row.


for (int index = 0; index < [Link]; index++) {
[Link]("The number of columns " + "in row " + index + " is "
+ numbers[index].length);
}

// Display the number of columns


[Link]("The number of rows is " + numbers[0].length);

numbers[0]
[3]

numbers[1]
[3]

numbers[2]
[3]
47
Sum Array Values/Elements
Summing the Rows of a Two-Dimensional Array
int[][] numbers = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
int total = 0; // Start the accumulator at 0.
for (int row = 0; row < [Link]; row++) {
for each row, reset the variable: total
total = 0; // Set the accumulator to 0.

// Sum a row.
for (int col = 0; col < numbers[row].length; col++)
total += numbers[row][col]; // Display the row's total.
[Link]("Total of row " + row + " is " + total);
}

Summing the Columns of a Two-Dimensional Array


int total; // Accumulator
for (int col = 0; col < numbers[0].length; col++) {
total = 0; // Set the accumulator to 0.

// Sum a column.
for (int row = 0; row < [Link]; row++)
total += numbers[row][col];
// Display the column's total.
[Link]("Total of column " + col + " is " + total);
} 48
Arrays with Three or More Dimensions
double[][][] seats = new double[3][4][3];

Array 3

Array 2

Array 1

49
Self Check
How do you declare and initialize a 4-by-4 array of integers?
Answer:
a. int array[][] = new int[4][4];
[Link][][] array= =new
int[][] array newint[][];
int[4][4]; Which option is correct?
c. int [4][4] array = new int[][];
d. int[][] array = new int[4][4];

How do you count the number of spaces in the tic-tac-toe board?


Answer:
int
intcount = 0;
count = 0; Suppose ROWS is number
for (int i = 0; i <= ROWS; i++) of rows,
for (int i = 0; i < ROWS; i++)
for (int j = 0; j <= COLUMNS; j++) And COLUMNS is number
for (int j = 0; j < COLUMNS; j++) of columns.
if (board[i][j] == ' ')
if (board[i][j] == ' ') count++; Can you fix this code?
count++;

50
Self Check - Answer
How do you declare and initialize a 4-by-4 array of integers?
Answer:
int[][] array = new int[4][4];
int array[][] = new int[4][4]; //it works, but not preferred style

How do you count the number of spaces in the tic-tac-toe board?


Answer:
int count = 0;
for (int i = 0; i < ROWS; i++)
for (int j = 0; j < COLUMNS; j++)
if (board[i][j] == ' ') count++;

51
ArrayList
Introduction to ArrayList
Retrieving Element
Changing and Inserting Element
Wrappers and Auto Boxing

52
Introduction to ArrayList
The ArrayList class manages a sequence of objects
Its length is dynamic. Can grow and shrink as needed
ArrayList class supplies methods for many common tasks,
such as inserting and removing elements
The ArrayList class is a generic class: Generic class is a class that
ArrayList<T> collects objects of type T: can be used with many
different types of data

ArrayList<BankAccount> accounts = new ArrayList<BankAccount>();


[Link](new BankAccount(1001));
[Link](new BankAccount(1015));
[Link](new BankAccount(1022));
The size of the array list increases after each call to add
Adds an object to the end of the array list

53
ArrayList
size method yields number of elements (current size of the array list)
int i = [Link](); // i = 3;

Cannot use primitive types as type parameters


There is NO ArrayList<int> or ArrayList<double>
But, there are ArrayList<Integer> and ArrayList<Double>

To use the array list, you have to import


import [Link];

54
Retrieving ArrayList Elements
Use get method
Index starts at 0
BankAccount anAccount = [Link](2);
// gets the third element of the array list

Bounds error if index is out of range


int i = [Link]();
anAccount = [Link](i); // Error
//legal index values are 0. . .i-1

55
Changing and Inserting Elements
Use method set to change an existing Element
BankAccount anAccount = new BankAccount(1729);
[Link](2, anAccount);
Set position 2 of the accounts array list to anAccount
Overwriting the existing Element with new Element
Use method add to add a new object to
the end of the array list
[Link](anAccount);

Use method add to insert a new Element at the index


[Link](i, a);

Insert at position i Inserted object 56


Removing Elements
remove method removes an element at an index
[Link](i)

57
int[] numArr = new int[5];
numArr[0] = 2;
numArr[2] = 5; //numArr[5] = 10; //ERROR

[Link]("----------- Array --------------");


for(int i = 0; i < [Link]; i++){
[Link]("value at index " + i + " is " + numArr[i]);
} ----------- Array --------------
value at index 0 is 2
value at index 1 is 0
value at index 2 is 5
value at index 3 is 0
value at index 4 is 0

List<String> nameList = new ArrayList<String>();


[Link]("a");
[Link]("b");

[Link]("----------- List --------------");


for(int i = 0; i < [Link](); i++){
[Link]("name at index "+i+" is "+ [Link](i));
}
----------- List --------------
name at index 0 is a
name at index 1 is b
File [Link]
01: import [Link]; Full source code for Class BankAccount
02: ([Link]) can be found in
03: /** Appendix A at the end of this
04: This program tests the ArrayList class. presentation
05: */
06: public class ArrayListTester
07: { No.1001, $0
08: public static void main(String[] args)
09: { No.1015, $0
10: ArrayList<BankAccount> accounts No.1008, $0
No.1729, $0
11: = new ArrayList<BankAccount>();
12: [Link](new BankAccount(1001));
13: [Link](new BankAccount(1015));
14: [Link](new BankAccount(1729)); 21: [Link]("First account number: "
15: [Link](1, new BankAccount(1008)); 22: + [Link]());
16: [Link](0); 23: [Link]("Expected: 1008");
17: 24: BankAccount last = [Link]([Link]() - 1);
18: [Link]("Size: " + [Link]()); 25: [Link]("Last account number: "
19: [Link]("Expected: 3"); 26: + [Link]());
20: BankAccount first = [Link](0); 27: [Link]("Expected: 1729");
28: }
29: } 61
File [Link] (cont.)

Output:
Size: 3
No.1008, $0
Expected: 3
No.1015, $0 First account number: 1008
No.1729, $0
Expected: 1008
Last account number: 1729
Expected: 1729

62
Self Check
How do you construct an array of 10 strings? An array list of strings?
Answer:
new String[10];
new ArrayList<String>();

What is the content of names after the following statements?


ArrayList<String> names = new ArrayList<String>();
[Link]("A");
[Link](0, "B");
[Link]("C");
[Link](1);
Answer: names contains the strings "B" and "C" at positions 0
and 1
63
Self Check
How do you construct an array of 10 strings? An array list of strings?
Answer:
new String[10];
new ArrayList<String>();

What is the content of names after the following statements?


ArrayList<String> names = new ArrayList<String>();
[Link]("A");
[Link](0, "B");
[Link]("C");
[Link](1);
Answer: names contains the strings "B" and "C" at positions 0
and 1
64
Wrappers & Auto-Boxing
You cannot insert primitive types directly into array lists
To treat primitive type values as objects, you must use wrapper classes:
// How to use wrapper class
Double d = 29.95;
// OR
Double d = new Double(29.95);

// ArrayList
ArrayList<double> data = new ArrayList<double>(); // ERROR!!

ArrayList<Double> data = new ArrayList<Double>(); // OK


[Link](29.95);
double d = [Link](0);

65
Wrappers
There are wrapper classes for all eight primitive types:

They are called wrappers because they are small classes that
has a primitive value instead. This is similar to a gift that we
wrap with a thin paper around it.

66
Auto-boxing
Auto-boxing: Starting with Java 5.0, conversion between primitive types and the corresponding
wrapper classes is automatic.

Double wrapper = 29.95;


// auto-boxing; same as Double wrapper = new Double(29.95);

double x = wrapper;
// auto-unboxing; same as double x = [Link]();
// ArrayList
ArrayList<Double> values = new ArrayList<Double>();
[Link](42.0);
Auto-boxing even works inside arithmetic expressions
double theAnswer = [Link](0); Double e = wrapper + 1;
Means:
Means:
auto-unbox d
auto-unbox wrapper into a double value
into a double
add 1
auto-box the result into a new Double
store a reference to the newly created wrapper object in e
67
Self Check
What is the difference between the types double and Double?
Answer: double is one of the eight primitive types. Double is a
class type.

Suppose data is an ArrayList<Double> of size > 0. How do you increment


the element with index 0?
Answer: [Link](0, [Link](0) + 1);

68
Self Check
What is the difference between the types double and Double?
Answer: double is one of the eight primitive types. Double is a
class type.

Suppose data is an ArrayList<Double> of size > 0. How do you increment


the element with index 0?
Answer: [Link](0, [Link](0) + 1);

69
ArrayList Algorithms
Enhanced for Loop
Adding a New Object
Counting Matched Objects
Finding a Given Object
Getting Maximum or Minimum Values

70
The Generalized for Loop
Works for ArrayLists too:
ArrayList<BankAccount> accounts = . . . ;
double sum = 0;
for (BankAccount a : accounts)
{
sum = sum + [Link]();
}
Equivalent to the following ordinary for loop:
double sum = 0;
for (int i = 0; i < [Link](); i++)
{
BankAccount a = [Link](i);
sum = sum + [Link]();
}

71
File [Link]
01: /** Full source code for Class Bank
02: This program tests the Bank class. ([Link]) can be found in
03: */ Appendix A at the end of this
presentation
04: public class BankTester
05: {
06: public static void main(String[] args)
07: {
08: Bank firstBankOfJava = new Bank();

// add new bank accounts


09: [Link](new BankAccount(1001, 20000));
10: [Link](new BankAccount(1015, 10000)); 1
11: [Link](new BankAccount(1729, 15000));
12:
13: double threshold = 15000;
// count number of account(s) that have balance at least 15000
14: int c = [Link](threshold);
15: [Link]("Count: " + c); 2
16: [Link]("Expected: 2");
17:
18: int accountNumber = 1015; 72
File [Link] (Cont.)
// find bank account of a given account number
19: BankAccount a = [Link](accountNumber); 3
20: if (a == null)
21: [Link]("No matching account");
22: else
23: [Link]("Balance of matching account: " + [Link]());
24: [Link]("Expected: 10000");
25:
// find account number that have the highest balance
26: BankAccount max = [Link]();
4
27: [Link]("Account with largest balance: "
28: + [Link]());
29: [Link]("Expected: 1001");
30: }
31: }

Output:
No.1001, $20,000
Count: 2
Expected: 2
No.1015, $10,000
Balance of matching account: 10000.0
Expected: 10000
No.1729, $15,000
Account with largest balance: 1001
Expected: 1001
73
Counting Matches
Check all elements and count the matches until you reach the end of the array list.

public class Bank


{
private ArrayList<BankAccount> accounts;

public void addAccount(BankAccount a)


{
[Link](a);
}

public int count(double atLeast)


{
int matches = 0;
for (BankAccount a : accounts)
{
if ([Link]() >= atLeast)
matches++; // Found a match
}
return matches;
}
. . .
} 74
Finding a Value
Check all elements until you have found a match.

public class Bank


{
public BankAccount find(int accountNumber)
{
for (BankAccount a : accounts)
{
if ([Link]() == accountNumber)
// Found a match return a;
}
return null; // No match in the entire array list
}
. . .
}
75
Finding the Maximum or Minimum
Initialize a candidate with the starting element
Compare candidate with remaining elements
Update it if you find a larger or smaller value
Example:
public BankAccount getMaximum(){
BankAccount largestYet = [Link](0);
for (int i = 1; i < [Link](); i++)
{
BankAccount a = [Link](i);
if ([Link]() > [Link]())
largestYet = a;
}
return largestYet;
}

Works only if there is at least one element in the array list . . .


If list is empty, return null:

if ([Link]() == 0) return null;


BankAccount largestYet = [Link](0); 76
. . .
Self Check
What does the find method do if there are two bank accounts with a
matching account number?
Answer: It returns the first match that it finds.
Would it be possible to use a "for each" loop in the getMaximum
method?
Answer: Yes, but the first comparison would always fail.
int[] numbers = {10, 5, 20};

int max = numbers[0]; // Set max to 10

for (int num : numbers) { // Loop starts at 10

if (num > max) { // First check: is 10 > 10?

max = num; }
}
77
Feature Array (int[]) ArrayList (ArrayList<Integer>)

Fixed: Must be declared at the Dynamic: Grows and shrinks


Size
start. automatically.

Objects only (uses Wrapper


Data Types Primitives (int) and Objects.
Classes).

Slower: Overhead from object


Performance Faster: Direct memory access.
management.

Syntax arr[0] = 10; [Link](10);

Size Method [Link] (Property) [Link]() (Method)

77
Appendix A: Full Source Code

78
File [Link]
01: /**
02: A bank account has a balance that can be changed by
03: deposits and withdrawals.
04: */
05: public class BankAccount
06: {
07: /**
08: Constructs a bank account with a zero balance
09: @param anAccountNumber the account number for this account
10: */
11: public BankAccount(int anAccountNumber)
12: {
13: accountNumber = anAccountNumber;
14: balance = 0;
15: }
16:
17: /**
18: Constructs a bank account with a given balance
19: @param anAccountNumber the account number for this account
20: @param initialBalance the initial balance
21: */

79
File [Link] (Cont.)
22: public BankAccount(int anAccountNumber, double initialBalance)
23: {
24: accountNumber = anAccountNumber;
25: balance = initialBalance;
26: }
27:
28: /**
29: Gets the account number of this bank account.
30: @return the account number
31: */
32: public int getAccountNumber()
33: {
34: return accountNumber;
35: }
36:
37: /**
38: Deposits money into the bank account.
39: @param amount the amount to deposit
40: */
41: public void deposit(double amount)
42: {
43: double newBalance = balance + amount;
44: balance = newBalance;
45: } 80
File [Link] (Cont.)
46:
47: /**
48: Withdraws money from the bank account.
49: @param amount the amount to withdraw
50: */
51: public void withdraw(double amount)
52: {
53: double newBalance = balance - amount;
54: balance = newBalance;
55: }
56:
57: /**
58: Gets the current balance of the bank account.
59: @return the current balance
60: */
61: public double getBalance()
62: {
63: return balance;
64: }
65:
66: private int accountNumber;
67: private double balance;
68: }
81
File [Link]
01: import [Link];
02:
03: /**
04: This bank contains a collection of bank accounts.
05: */
06: public class Bank
07: {
08: /**
09: Constructs a bank with no bank accounts.
10: */
11: public Bank()
12: {
13: accounts = new ArrayList<BankAccount>();
14: }
15:
16: /**
17: Adds an account to this bank.
18: @param a the account to add
19: */
20: public void addAccount(BankAccount a)
21: {
22: [Link](a);
23: }
82
File [Link] (cont.)
24:
25: /**
26: Gets the sum of the balances of all accounts in this bank.
27: @return the sum of the balances
28: */
29: public double getTotalBalance()
30: {
31: double total = 0;
32: for (BankAccount a : accounts)
33: {
34: total = total + [Link]();
35: }
36: return total;
37: }
38:
39: /**
40: Counts the number of bank accounts whose balance is at
41: least a given value.
42: @param atLeast the balance required to count an account
43: @return the number of accounts having least the given balance
44: */
45: public int count(double atLeast)
46: {
83
File [Link] (cont.)
47: int matches = 0;
48: for (BankAccount a : accounts)
49: {
50: if ([Link]() >= atLeast) matches++; // Found a match
51: }
52: return matches;
53: }
54:
55: /**
56: Finds a bank account with a given number.
57: @param accountNumber the number to find
58: @return the account with the given number, or null if there
59: is no such account
60: */
61: public BankAccount find(int accountNumber)
62: {
63: for (BankAccount a : accounts)
64: {
65: if ([Link]() == accountNumber) // Found a match
66: return a;
67: }
68: return null; // No match in the entire array list
69: }
84
70:
File [Link] (cont.)
71: /**
72: Gets the bank account with the largest balance.
73: @return the account with the largest balance, or null if the
74: bank has no accounts
75: */
76: public BankAccount getMaximum()
77: {
78: if ([Link]() == 0) return null;
79: BankAccount largestYet = [Link](0);
80: for (int i = 1; i < [Link](); i++)
81: {
82: BankAccount a = [Link](i);
83: if ([Link]() > [Link]())
84: largestYet = a;
85: }
86: return largestYet;
87: }
88:
89: private ArrayList<BankAccount> accounts;
90: }

85
File [Link]
01: /**
02: A 3 x 3 tic-tac-toe board.
03: */
04: public class TicTacToe
05: {
06: /**
07: Constructs an empty board.
08: */
09: public TicTacToe()
10: {
11: board = new String[ROWS][COLUMNS];
12: // Fill with spaces
13: for (int i = 0; i < ROWS; i++)
14: for (int j = 0; j < COLUMNS; j++)
15: board[i][j] = " ";
16: }
17:
18: /**
19: Sets a field in the board. The field must be unoccupied.
20: @param i the row index
21: @param j the column index
22: @param player the player ("x" or "o")
23: */ 86
File [Link] (Cont.)
24: public void set(int i, int j, String player)
25: {
26: if (board[i][j].equals(" "))
27: board[i][j] = player;
28: }
29:
30: /**
31: Creates a string representation of the board, such as
32: |x o|
33: | x |
34: | o|
35: @return the string representation
36: */
37: public String toString()
38: {
39: String r = "";
40: for (int i = 0; i < ROWS; i++)
41: {
42: r = r + "|";
43: for (int j = 0; j < COLUMNS; j++)
44: r = r + board[i][j];
45: r = r + "|\n";

87
File [Link] (Cont.)
46: }
47: return r;
48: }
49:
50: private String[][] board;
51: private static final int ROWS = 3;
52: private static final int COLUMNS = 3;
53: }

88
File [Link]
01: import [Link];
02:
03: /**
04: This program runs a TicTacToe game. It prompts the
05: user to set positions on the board and prints out the
06: result.
07: */
08: public class TicTacToeRunner
09: {
10: public static void main(String[] args)
11: {
12: Scanner in = new Scanner([Link]);
13: String player = "x";
14: TicTacToe game = new TicTacToe();
15: boolean done = false;
16: while (!done)
17: {
18: [Link]([Link]());
19: [Link](
20: "Row for " + player + " (-1 to exit): ");
21: int row = [Link]();
22: if (row < 0) done = true;
23: else
24: { 89
File [Link] (Cont.)
25: [Link]("Column for " + player + ": ");
26: int column = [Link]();
27: [Link](row, column, player);
28: if ([Link]("x"))
29: player = "o";
30: else
31: player = "x";
32: }
33: }
34: }
35: }

90

You might also like