You are on page 1of 20

CHAPTER 5: ARRAYS OF

OBJECTS

PROGRAMMING 2
COMP 112
Introduction
2

● Arrays in Java are the ways to store collections of items into


a single unit. The array has some number of slots, each of
which holds an individual item. You can add and delete
items to those slots as needed.
● To create an array in Java, you use three steps:
1. Declare a variable to hold the array.
String[] cars;
2. Create a new array object and assign it to the array variable.
cars = new String[3];
3. Store things in that array.
cars[0] = "Toyota";
cars[1] = "Nissan";
cars[2] = "Ford";
Programming 2 COMP 112 Spring 20-21
Creating arrays of objects – part 1
3

● To create an array object and assign it to that variable.


There are 2 ways to do this:
1. Using new
2. Directly initializing the contents of that array
The first way
is to use the new operator to create a new instance of an
array:
String[] names = new String[10];
That line creates a new array of Strings with 10 slots (sometimes called
elements). When you create a new array object using new, you must
indicate how many slots that array will hold. This line does not put actual
String objects in the slots-you'll have to do that later.

Programming 2 COMP 112 Spring 20-21


Creating arrays of objects – part 2
4

● When you create an array object using new, all its slots are
initialized for you (null for objects).
● You can then assign actual values or objects to the slots in
that array.
The second way
create an array and initialize its contents at the same time.
Instead of using new to create the new array object,
enclose the elements of the array inside braces, separated
by commas.
● For example:
String[] cars = {"Toyota", "Nissan", "Ford", "Mazda"};

Programming 2 COMP 112 Spring 20-21


Array of Cards – part 1
5

Instance Variables:
— If we want to define a class to represent a playing card, we
may declare the instance variables rank and suit and the
constructor.

— The instance variables are private: we can access them from


inside this class, but not from other classes.
Programming 2 COMP 112 Spring 20-21
Array of Cards – part 1
6

Class Variables
public class Card {
public static final String[] RANKS = {
null, "Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King"};
public static final String[] SUITS = {"Clubs", "Diamonds",
"Hearts", "Spades"};
public String toString() {
return RANKS[this.rank] + " of " + SUITS[this.suit];
}
}
— Note: Class variables are often used to store constant values that
are needed in several places. In that case, they should also be
declared as final. Note that whether a variable is static or final
involves two separate considerations: static means the variable is
shared, and final means the variable is constant.
Programming 2 COMP 112 Spring 20-21
Array of Cards – part 2
7

— you can create an array of Card objects. The following


statement creates an array of 52 cards:
Card[] cards = new Card[52];

— Although we call it an “array of cards”, the array contains


references to card.
— It does not contain the Card objects them selves. Initially
the references are all null.

Programming 2 COMP 112 Spring 20-21


Arrays of Cards – part 3
8

— You can access the elements of the array in the usual


way:
if (cards[0] == null) {
System.out.println("No card yet!");
}

— But if you try to access the instance variables of non-


existent Card objects, you will get a
NullPointerException.

Programming 2 COMP 112 Spring 20-21


Array of Cards – part 4
9

— One way to populate the array is as following :

— The outer loop iterates suits from 0 to 3. For each suit, the
inner loop iterates ranks from 1 to 13. Since the outer loop
runs 4 times, and the inner loop runs 13 times for each suit,
the body is executed 52 times.
Programming 2 COMP 112 Spring 20-21
Sequential search – part 1
10

● Sequential search is the only method that can be used to


find a value on unsorted or unordered data. It usually
starts at the first element and walks through the array or
list until it finds the value that is looking for and returns
its index, or loops until the end of the array or list and
then returns a -1.

Programming 2 COMP 112 Spring 20-21


Sequential search – part 2
11

● Java provides equals method to test whether two objects


are equivalent.
● When we test search method, we always get -1 as the
output because equals method is not suitable for our class.
● It is helpful to create our own equals method version for
the classes that we define.

Programming 2 COMP 112 Spring 20-21


Sequential search – part 3
12

● The method returns as soon as it discovers the card, which


means we don’t have to traverse the entire array if we find
the target.
● If we get to the end of the loop, we know the card is not in
the array.
● Sequential search is relatively inefficient, especially for
large arrays.

Programming 2 COMP 112 Spring 20-21


Binary search – part 1
13

● Binary Search:
Search a sorted array by repeatedly dividing the search
interval in half. Begin with an interval covering the whole
array. If the value of the search key is less than the item in
the middle of the interval, narrow the interval to the lower
half. Otherwise narrow it to the upper half. Repeatedly
check until the value is found, or the interval is empty.
● Advantages:
This algorithm is much faster than sequential search,
because it rules out half of the remaining elements each time
you make a comparison.

Programming 2 COMP 112 Spring 20-21


Binary search – part 2
14

Programming 2 COMP 112 Spring 20-21


Binary search – part 3
15

● First, we declare low and high variables to represent the


range we are searching. Initially we search the entire array,
from 0 to cards.length - 1.
● Inside the while loop, we repeat the 4 steps of binary search:
1. Choose an index between low and high – call it mid – and
compare the card at mid to the target.
2. If you found the target, return its index (which is mid).
3. If the card at mid is lower than the target, search the range
from mid + 1 to high.
4. If the card at mid is higher than the target, search the range
from low to mid - 1.
Programming 2 COMP 112 Spring 20-21
Binary search – part 3
16

● If low exceeds high, there are no cards in the range, so we


terminate the loop and return -1.
● Notice that this algorithm only depends on the compareTo
method of the object. We can apply this same code to any
object that provides a compareTo method.

Programming 2 COMP 112 Spring 20-21


comparetTo() method
17

● The natural ordering is defined by implementation of the


compareTo() method which determines how the current
object (obj1) is compared to another (obj2) of the same
type. The order is based on return value (an integer number,
say x) of the compareTo() method:

1. obj1 > obj2 if x > 0.


2. obj1 < obj2 if x < 0.
3. obj1 equals obj2 if x = 0.

Programming 2 COMP 112 Spring 20-21


comparetTo() method
18

Programming 2 COMP 112 Spring 20-21


Recursion version of Binary Search
19
public static int binarySearch(Card[] cards, Card target, int low, int high) {
if (high < low) {
return -1;
}
int mid = (low + high) / 2; // step 1
int comp = cards[mid].compareTo(target);
if (comp == 0) { // step 2
return mid;
} else if (comp < 0) { // step 3
return binarySearch(cards, target, mid + 1, high);
} else { // step 4
return binarySearch(cards, target, low, mid -1);
}
}
Programming 2 COMP 112 Spring 20-21
Important Definitions
20

● Class variable:
A variable declared within a class as static. There is only one
copy of a class variable, no matter how many objects there
are.
● Sequential search:
An algorithm that searches array elements, one by one,
until a target value is found.
● Binary search:
An algorithm that searches a sorted array by starting in the
middle, comparing an element to the target, and
eliminating half of the remaining elements
Programming 2 COMP 112 Spring 20-21

You might also like