06 Arrays and ArrayLists
06 Arrays and ArrayLists
Unit 6
1
Summary: Lecture 05 (OOP)
• Defining Class
• Instantiation of objects
• Variables
• Instance variables
• Local variables
• Static/class variables
• this. Variable (object reference)
• Methods
• Constructor
• Static/class method
• Public method
• Setter and getter methods
• Method overloading
• Access Modifiers
• Public
• Private
• Protected
• Default 2
Outline
• Arrays
• Arrays of Objects
• Array Class
• ArrayList Class
• Exception Handling
33
Basic Concepts of Arrays
• A group of variables/elements of the same type
• Arrays are objects
– Created with the new keyword
– Memory allocation of an array is contiguous (elements
next to each others, not randomly placed in memory)
• The array size is fixed/constant
– Cannot be resized
– The number of elements in the array can be retrieved
using the instance variable length
• An array can be of any primitive or object type
4
Declaring and creating arrays
num[0] 0
int[] num = new int[3]; num num[1] 0 Allocation
Declaration Array Creation num[2] 0
7
You may initialize an array explicitly
MEMORY
[0] 1
[1] 2
numbers [2] 3
[3] 4
[4] 5
8
Array elements are indexed
int[] numbers = new int[5];
MEMORY
[0] 1 numbers[0] = 1;
[1] 2 numbers[1] = 2;
numbers [2] 0
[3] 0
[4] 0
9
Arrays can be class attributes
public class Student {
private int[] grades;
...
}
return array;
}
//example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// displays Volvo
System.out.println(cars.length); // displays 4
11
Arrays are objects, thus
int[] a = {1, 2, 3};
int[] b;
13
Example - Method that tests for array equality
14
Enhanced for loop
• The enhanced for loop (also called a "for each" loop) allows you to iterate
through the elements of an array or a list without using a counter.
• The syntax of an enhanced for statement is:
for {var item : arrayName) {
statement;
Note: for-each loop is easier to write, it does not require a counter (using the
length property), and it is more readable.
15
Array Search
16
Array of Objects Example
Book[] books = new Book[2];
17
The Arrays class and its API
18
Arrays.sort(a);
19
//search for x in a
20
Multidimensional Arrays
• Two-dimensional arrays are often used to represent
tables of values with data arranged in rows and
columns.
• Example two-dimensional arrays with 3 rows and 4
columns
21
Multidimensional Arrays (Cont.)
• A multidimensional array b with 3 rows and 4 columns
int[][] b = new int[3][4];
22
ArrayLists
• Problem with arrays
– You must know the array size when you create the
array
– Array size cannot change once created.
• Solution:
– Use ArrayList: they stretch as you add elements to
them or shrink as you remove elements from
them
– Similar to arrays + allow Dynamic resizing
23
ArrayList Class
• ArrayList<T> in package java.util can dynamically
change its size to accommodate more elements.
– T is a placeholder for the type of element stored
in the collection.
24
ArrayList methods
• Create empty list
new ArrayList<>()
• Add entry to end
add(value)
• Retrieve element at index
get(index)
• Check if element exists in list
contains(element)
• Remove element
remove(index) or remove(element)
• Get the number of elements
size()
• Remove all elements
clear() 25
ArrayList Example
import java.util.ArrayList; // Don't forget this import
26
ArrayList Example
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.get(2); //Ford
cars.set(2,“Toyota”); // replace “Ford” by “Toyota”
cars.remove(0); //”Volvo” removed
cars.size(); //to find out how many elements an ArrayList has
for (String car : cars) { //for-each loop
System.out.println(car);
}
cars.clear(); //Remove all elements from ArrayList
}
}
27
Other Types in ArrayList
• Elements in an ArrayList are actually objects.
• In the examples in previous slide, we created elements
(objects) of type "String".
• Remember that a String in Java is an object (not a primitive
type).
• To use other types, such as int, you must specify an
equivalent wrapper class: Integer.
• For other primitive types, use: Boolean for boolean,
Character for char, Double for double, etc.
28
ArrayList Example with Integer
import java.util.ArrayList;
29
Sort an ArrayList of String
• Another useful class in the java.util package is the Collections class, which
include the sort() method for sorting lists alphabetically or numerically:
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
//alternative solution
for(Book temp: books) {
System.out.println(temp.getTitle());
}
books.set(0, new Book(“The Man and the Sea"); //replaces item at position 0
books.remove(1);
32
Variable-Length Argument Lists
• Variable-length argument lists can be used to create
methods that receive an unspecified number of
arguments.
– Parameter type followed by an ellipsis (...) indicates that
the method receives a variable number of arguments of that
particular type.
• A variable-length argument list is treated as an array
within the method body. The number of arguments in
the array can be obtained using the array’s length
attribute.
33
Variable-Length Argument Lists - Example
// Variable-Length Argument Lists - Example
public static double average(double... numbers) {
double total = 0.0;
for(var num : numbers) {
total += num;
}
return total / numbers.length;
}
34
What is an Exception?
• An exception indicates a problem that occurs while a
program executes.
• When the Java Virtual Machine (JVM) or a method
detects a problem, such as an invalid array index or an
invalid method argument, it throws an exception.
• e.g., trying to access an array element outside the
bounds of the array.
Java doesn’t allow this.
JVM checks that array indices to ensure that they are >= 0
and < the array’s size. This is called bounds checking.
If a program uses an invalid index, JVM throws an exception
to indicate that an error occurred in the program at
execution time.
35
Handling Exceptions
• Exception handling helps you create fault-
tolerant programs that can resolve (or handle)
exceptions.
• To handle an exception, place any code that
might throw an exception in a try statement.
• The catch block contains the code that handles
the exception.
You can have many catch blocks to handle different
types of exceptions that might be thrown in the
corresponding try block
An exception object’s .toString or .getMessage
method returns the exception’s error message
36
Handling Exceptions – Example 1
try {
int nums[] = {3, 5, 9};
System.out.println(nums[3]);
System.out.println("nums array size: " +
nums.length);
}
catch (IndexOutOfBoundsException ex){
System.err.println(ex.getMessage());
}
• The program attempts to access an element outside the bounds of the array
the array has only 3 elements (with an index 0 to 2).
• JVM throws ArrayIndexOutOfBoundsException to notify the program of this
problem.
• At this point the try block terminates and the catch block begins executing
if you declared any local variables in the try block, they’re now out of scope.
37
Handling Exceptions – Example 2
try {
int[] nums = null;
System.out.println("nums array size: " + nums.length);
}
catch (NullPointerException ex){
System.err.println(ex.toString());
}
38
Handling Exceptions - Example 3
//This will generate an error, because myNumbers[10] does not exist.
public class Main {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}
//we can use try...catch to catch the error and execute some code to handle it
39
Handling Exceptions with Finally – Example 4
The finally statement lets you execute code, after try...catch,
regardless of the result:
40