Lecture04 2025 Array ArrayList
Lecture04 2025 Array ArrayList
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
// accounts array
// BankAccouunt Object
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
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.
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;
15
Self Check
What elements does the data array contain after the following statements?
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.
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.
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.
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.
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.
panel
23
public class BankAccount {
public int accountNumber; Account Number
public double balance; Balance
/**
* 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};
/** /**
* 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?
Why is the "for each" loop not an appropriate shortcut for the
following ordinary for loop?
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.");
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
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.
37
Delete an Element from an Array
[Link](src, srcPos, dest, destPos, length);
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:
99
42
Initialize a 2D Array
int[][] numbers = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
visualization
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:
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;
}
}
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);
}
// 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];
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
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
53
ArrayList
size method yields number of elements (current size of the array list)
int i = [Link](); // i = 3;
54
Retrieving ArrayList Elements
Use get method
Index starts at 0
BankAccount anAccount = [Link](2);
// gets the third element of the array list
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);
57
int[] numArr = new int[5];
numArr[0] = 2;
numArr[2] = 5; //numArr[5] = 10; //ERROR
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>();
// ArrayList
ArrayList<double> data = new ArrayList<double>(); // ERROR!!
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 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.
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.
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();
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.
max = num; }
}
77
Feature Array (int[]) ArrayList (ArrayList<Integer>)
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