You are on page 1of 30

SSD3: Object-Oriented Programming and

Design

Object-Oriented Programme 1
Unit 2. Class Implementation
 2.1 Implementing Classes
 2.2 Collections
 2.3 Advanced Class Design

 Assessments
 Exam 2

Object-Oriented Programme 2
Collections 集合
 2.2.1 Arrays
 2.2.2 ArrayList and Iterators
 2.2.3 Implementing the Collections of the Library
System

 Assessments
 Practical Quiz 6
 Practical Quiz 7
 Multiple-Choice Quiz 4
 Exercise 4

Object-Oriented Programme 3
2.2.1 Arrays
 Arrays
 Declaring
and Using Arrays
 Example Using Arrays

Object-Oriented Programme 4
Arrays
 An array is a homogeneous aggregate , a collection of data
(each of which is the same type).
 In Java, an array can contain a set of primitives or a set of
object references.
 Each item in an array is called an element.
 To access an element in an array, use the bracket operator (
[ ] ) and an integer index value that indicates the location of
the element in the array.
 The first element in an array has an index of 0, the second
has an index of 1, and so on.
 Consequently, the indexes in an array of n elements will
range from 0 to n - 1.
 Array elements are stored contiguously in memory.

Object-Oriented Programme 5
Declaring and Using Arrays
 An array is declared by specifying the type of its elements,
followed by “ [ ] ”:
 int[ ] ages;
 The type of the elements in the array is int.
 The name of the array is the identifier ages.
 String[ ] names;
 declares a String array, a collection of String references.
 The variables ages and names are reference variables and
their values are initially null.
 Each will remain null until an array object is created. (In
Java, arrays are implemented as objects.)

Object-Oriented Programme 6
create an array object
 To create an array object, use the new operator,
followed by the type of the elements and the array's
desired size.
 The array size must be non-negative interger.

ages = new int[5];


names = new String[3];
 When a new array object is created, its elements
are initialized to their default values.
 the elements of the array ages are initialized to
zero 基本类型
 the elements of the array names are initialized to
null. 对象引用类型
Object-Oriented Programme 7
create an array object
 An array object contains a public instance variable called
length
 indicates the number of elements in the array.
 the length of an array object can never change.
 However, an array reference can be changed so that it
refers to another array object, with a different length.
int[] values = new int[5];
int[] biggerArray = new int[10];
int nextIndex = 0;
...
if (nextIndex >= values.length) {
values = biggerArray;
}

Object-Oriented Programme 8
another way to create an array object
 the array declaration can include an initializer, a
comma-separated list of initial element values
within “{ }”.
 An initializer can only be used in a declaration
statement.
int[] ages = {21, 19, 35, 27, 55};
String[] names = {"Bob", "Achebe", null};
 The length of the array is deduced from the number
of items in the initializer. 这里的数组声明没有元素
个数,由 jvm 计算得出

Object-Oriented Programme 9
using array element
 ArrayIndexOutOfBoundsException
 an array element is accessed using the “ [ ] ” and
an index.
ages[2] // the third element, index 2 indicates
the third element in the array:
 The Java Virtual Machine (JVM) will throw an
ArrayIndexOutOfBoundsException if a program
tries to use an invalid index.
A negative index is always invalid.
If an array contains n elements, then an index of n or
greater is invalid. (个数一定小于 n )

Object-Oriented Programme 10
using in for - loop
 Arrays are typically traversed in sequential order using for-
loops.
int[] values = new int[5];
for (int i = 0; i < values.length; ++i) {
values[i] = i * i;
}
 The loop control variable i serves two purposes in the loop
body:
 it is used as the array index and
 it is used to calculate the value of each array element.
 values.length is part of the loop termination condition.

Object-Oriented Programme 11
Example Using Arrays
 Sample code ( Dictionary.java)

Object-Oriented Programme 12
Note of sample code
 The words of the dictionary are stored in a String array. At line 77, the
method addWord adds a word to the array. Initially, the array can hold
up to five strings. If addWord is called and the array is full, addWord
creates a new array (which is twice the size of the current array), copies
the contents of the current array into the new array, and then updates
the array reference so that it refers to the new array.
 At line 104, the method hasWord determines if the specified word is part
of the dictionary. It searches the array linearly, beginning with the 0th
element (that is, the first element at index 0).
 At line 33, the method main tests the implementation of class Dictionary
using two arrays: knownWords and unknownWords. At line 42, the for-
loop adds the strings in the array knownWords to the dictionary. At line
45, the for-loop verifies that the strings have been added to the
dictionary. Finally, at line 52, the for-loop verifies that the strings in the
array unknownWords are not part of the dictionary.

Object-Oriented Programme 13
2.2.2 Vectors and Iterators
 Vectors
 Iterators
 Collections and Iterators

Object-Oriented Programme 14
Vectors
 The class java.util.Vector implements a collection of
objects that can grow to accommodate new items
when the collection is full.
 The objects in the vector can be accessed using an
integer index.

Object-Oriented Programme 15
some of the methods defined in class Vector
 Vector().
 Constructs an empty vector.
 int size().
 Returns the number of objects in the vector.
 boolean isEmpty().
 Determines if there are no objects in the vector.
 boolean contains(Object elem).
 Determines if the specified object is an element of the
vector (as determined by the method equals).
 boolean add(Object o).
 Appends the specified object to the end of the vector.

Object-Oriented Programme 16
some of the methods defined in class Vector
 void add(int index, Object element).
 Inserts the specified object at the specified index position, shifting
any subsequent elements to the right (adds one to their indices).
 Object get(int index).
 Returns the object at the specified position.
 public Object set(int index, Object element).
 Replaces the element at the specified index position with the
specified object.
 public boolean remove(Object o).
 Removes the first occurrence of the specified object (using method
equals), shifting any subsequent elements to the left (subtracts one
from their indices).
 Object remove(int index).
 Returns the object at the specified position after first removing it from
the vector and shifting any subsequent elements to the left
(subtracts one from their indices).

Object-Oriented Programme 17
Class Vector holds references
 Class Vector holds references to instances of class
java.lang.Object. The Vector method add accepts a
reference to an instance of any class that descends from
class java.lang.Object: 你可以放入任意类型的对象引用
Vector vector = new Vector();
vector.add("Hello");
vector.add(new Integer(10));
vector.add(new Employee("John Smith");
 To retrieve the elements in this vector, the Object references
returned by the Vector method get must be cast:
String string = (String) vector.get(0);
Integer integer = (Integer) vector.get(1);
Employee employee = (Employee) vector.get(2);

Object-Oriented Programme 18
Iterators 迭代器
 The Vector method iterator() returns a
java.util.Iterator object over the elements of the
vector.
 An iterator is an object for traversing (遍历) a
vector from start to finish.
 using iterators you can safely removing elements
from the vector during the traversal.

Object-Oriented Programme 19
Some methods of java.util.Iterator
 boolean hasNext(). 是不是很熟悉? HasSth...()
 Returns true if the iteration has more elements.
 Object next().
 Returns the next element in the iteration.
 void remove().
 Removes from the vector the last element
returned by the iterator.
 This method throws the IllegalStateException, if
next()has not been called, or
remove() has already been called after the last call to
the method next().

Object-Oriented Programme 20
Sample
 Source code(DictionaryWithVector.java)
 The words of the dictionary are stored in a vector. In line 78,
method addWord calls the Vector method add to add a word
to the dictionary.

 At line 91, method hasWord calls the Vector method


contains to determine if the specified word is part of the
dictionary.

 At line 104, method getStartsWith uses an iterator to


traverse the dictionary and returns a vector of all words in
the dictionary that start with the specified prefix.

Object-Oriented Programme 21
Collections and Iterators
 Array elements are accessed using indexes. Java
collections, like Vector, provide another mechanism
for accessing elements: iterators.

Object-Oriented Programme 22
example

 The collection is stored in the Client attribute accounts.


 addAccount() stores an instance of class BankAccount in the collection.
 getAccountsIterator() returns an iterator over the bank accounts in the
collection.
 getNumberOfBankAccounts() returns the number of bank accounts in
the collection.
 Source code(Client.java)
 帐号的数量可灵活变化,用数组好不好呢?

Object-Oriented Programme 23
2.2.3 Implementing the Collections of the
Library System
 Library System Collection Classes
 Class Catalog
 Class BorrowedItems
 Class BorrowerDatabase
 Complete Library System

Object-Oriented Programme 24
Library System Collection Classes

Object-Oriented Programme 25
classes use collections
 Thefollowing classes use collections:
 Catalog
 BorrowedItems
 BorrowerDatabase

Object-Oriented Programme 26
Class Catalog
 The class Catalog uses a collection of CatalogItem
instances.
 Instance variables:
 items. A vector that contains references to CatalogItem instances.
 Constructor and methods:
 public Catalog(). Creates the vector items, which is initially empty.
 public void addItem(CatalogItem catalogItem) . Adds the specified
item to the catalog.
 public CatalogItem getItem(String code). Returns a reference to the
CatalogItem instance with the specified code. Returns null if there
are no items in the catalog with the specified code.
 public Iterator getItemsIterator(). Returns an iterator over the items in
the catalog.
 public int getNumberOfItems(). Returns the number of items in the
catalog.
 Source code ( Catalog.java) 27
Object-Oriented Programme
Class BorrowedItems
 The class BorrowedItems models the list of items
checked out by a particular borrower. It uses a
collection of CatalogItem instances.
 Instance variables:
 items. A vector that contains references to CatalogItem instances.
 Constructor and methods:
 public BorrowedItems(). Creates the vector items, which is initially
empty.
 public void addItem(CatalogItem catalogItem). Add the specified item
to the list of items check out by the borrower.
 public CatalogItem getItem(String code). Returns a reference to the
CatalogItem instance with the specified code. Returns null if there
are no items in the list with the specified code.
 public Iterator getItemsIterator(). Returns an iterator over the
borrowed items.
 public int getNumberOfItems(). Returns the number of borrowed
items.
 Source code(BorrowedItems.java)
Object-Oriented Programme 28
Class BorrowerDatabase
 The class BorrowerDatabase models a database of
borrowers. It uses a collection of Borrower
instances.
 Instance variables:
 borrowers. A vector that contains references to Borrower instances.
 Constructor and methods:
 public BorrowerDatabase(). Creates the vector borrowers, which is
initially empty.
 public String addBorrower(Borrower borrower). Add the specified
borrower to the database.
 public Borrower getBorrower(String id). Returns a reference to the
Borrower instance with the specified id. Returns null if there are no
borrowers in the database with the specified id.
 public Iterator getBorrowersIterator(). Returns an iterator over the
borrowers in the database.
 public int getNumberOfItems(). Returns the number of borrowers in
the database.
 Source code (BorrowerDatabase.java)
Object-Oriented Programme 29
Complete Library System
 The following files implement the other classes in
the library system:
 Book.java
 Recording.java
 CatalogItem.java
 Borrower.java
 LibrarySystem.java

Object-Oriented Programme 30

You might also like