Returns the {@link CatalogItem}

Download Report

Transcript Returns the {@link CatalogItem}

Object-Oriented Design and Programming (Java)
Topics Covered Today
• 2.2 Collections
– 2.2.1 Arrays
– 2.2.2 Vectors and Iterators
– 2.2.3 Implementing the Collections of the Library
System
2
What is a Collection?
• A “collection” object — sometimes called a container —
is simply an object that groups multiple elements into a
single unit
• Collections are used to store, retrieve, manipulate, and
communicate aggregate data
• Typically, they represent data items that form a natural
group, such as a poker hand (a collection of cards), a mail
folder (a collection of letters), or a telephone directory (a
mapping of names to phone numbers).
3
Array
• Group data objects of the same type
– 数组是同类数据的集合
– 数组中的每一项叫元素(element),用[]和下标值
(整型)来访问,下标值从0开始;
• Declare arrays
char ch[]; or char[] ch;
– Create space for a reference
– Remember an array is an object not memory reserved
for primitive types
4
Creating an Array
• Use the new keyword to create an array object
new dataType[arraySize]
int[] anArray = new int[10];
• The statement in the sample program allocates an array
with enough memory for ten integer elements and assigns
the array to the variable anArray declared earlier.
5
Accessing an Array Element
• Now that some memory has been allocated for the array,
the program assign values to the array elements:
for (int i=0; i<anArray.length; i++) {
anArray[i] = i;
System.out.print(anArray[i] + " ");
}
• Note that in Java, array indices begin at 0 and end at the
array length minus 1.
6
Example Array
class ArrayDemo {
public static void main(String[] args) {
// declare an array of integers and create an array of integers
int[] anArray = new int[10];
// assign a value to each array element and print
for (int i=0; i< anArray.length; i++) {
anArray[i] = i;
System.out.print(anArray[i] + " ");
}
System.out.println();
}
}
7
Initializing an array
• Java provides a shortcut syntax for creating and
initializing an array.
– int[] x = { 1, 3, 5, 7, 9 };
– String[] strDays = { “Mon, ”Wed”, ”Fri” };
– boolean[] answers = { true, false, true, true };
8
Arrays Summary
• The size of an array is fixed at the time it is created and
can not be changed afterwards.
• Any attempt to access an element outside the length of an
array will throw an IndexOutOfBoundsException.
• All the elements stored in the array must be of the same
type or class.
• An array has a public attribute called length which
indicates the number of elements that it contains.
• The elements contained in an array can also be arrays!
(And the elements in those arrays can be arrays, and so
on …). These are known as multi-dimensional
9
java.util.Vector
• Package java.util
• The Vector class implements a growable array of
objects.
– The size of a Vector can grow or shrink as needed to
accommodate adding and removing items after the
Vector has been created.
– The objects in the vector can be accessed using an
integer index.
10
methods defined in class Vector
•
•
•
•
•
•
•
•
•
•
Vector(). 构造器;
int size().返回vector中对象的个数;
boolean isEmpty(). 判断vector中是否还有对象;
boolean contains(Object elem). 判断制定的对象是否在vector中;
boolean add(Object o). 将指定的对象添加在vector的末尾;
void add(int index, Object element). 在指定的位置添加指定的对象,向
后移动其他的元素;
Object get(int index). 返回指定位置的对象;
public Object set(int index, Object element). 用指定的对象替换指定位
置的对象元素;
public boolean remove(Object o). 将指定的对象在第一次出现的位置处
删除,后面的元素依次前移;
Object remove(int index). 将指定位置的对象从vector移走并且后面的
对象依次前移后,将该对象返回;
11
using Vector
import java.util.Vector;
public class test {
public static void main(String[] args) {
Vector vector = new Vector();
vector.add("Hello");
vector.add(new Integer(10));
vector.add(new Employee("John Smith"));
String string = (String) vector.get(0);
Integer integer = (Integer) vector.get(1);
Employee employee = (Employee) vector.get(2);
System.out.println(string);
System.out.println(integer);
System.out.println(employee);
} }
12
Generic Types in Java 5
• When using a collection (e.g., LinkedList, HashSet,
HashMap), we generally have a single type T of elements
that we store in it (e.g., Integer, String)
• Before 1.5, when extracting an element, had to cast it to T
before we could invoke T's methods
• Compiler could not check that the cast was correct at
compile-time, since it didn't know what T was
• Inconvenient and unsafe, could fail at runtime
13
Generic Types in Java 5.
• Generics in Java 1.5 provide a way to
communicate T, the type of elements in a
collection, to the compiler
– Compiler can check that you have used the collection
consistently
– Result: safer and more-efficient code
14
Vector (Using Generic Type)
• Before JDK5.0:
String string = (String) vector.get(0);
• JDK5.0
Vector<String> vector = new Vector<String>();
vector.add("Hello");
String hello = vector.elementAt(0);
15
The ArrayList Class
• The class java.util.ArrayList<E> implements a
collection of objects that can grow to
accommodate new items when the collection is
full.
16
Methods Defined in Class ArrayList
•
•
•
•
•
•
•
•
•
•
ArrayList(). Constructs an empty collection.
int size(). Returns the number of objects in the collection.
boolean isEmpty(). Determines if there are no objects in the collection.
boolean contains(Object elem). Determines if the specified object is an
element of the collection (as determined by the method equals).
boolean add(E o). Appends the specified object to the end of the collection.
void add(int index, E element). Inserts the specified object at the specified
index position, shifting any subsequent elements to the right (adds one to
their indices).
E get(int index). Returns the object at the specified position.
public E set(int index, E 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).
E remove(int index). Returns the object at the specified position after first
removing it from the collection and shifting any subsequent elements to the
left (subtracts one from their indices).
17
ArrayList Example
ArrayList<Employee> employees =
new ArrayList<Employee>();
employees.add(new Employee("John Smith"));
employees.add(new Employee("Mary Williams"));
employees.add(new Employee("Peter Jefferson"));
Employee firstEmployee = employees.get(0);
18
ArrayList Example
ArrayList<Integer> numbers =
new ArrayList<Integer>();
numbers.add(1);
int num = numbers.get(0);
19
java.util.Iterator<E>
• An iterator is an object for traversing a vector
from start to finish.
– Iterator是一个用于遍历Vector中的每个元素的对象
• The ArrayList method iterator() returns a
java.util.Iterator<E> object over the elements
• Methods of Iterator:
– boolean hasNext(). Returns true if the iteration has
more elements.
– E next(). Returns the next element in the iteration.
– void remove(). Removes from the collection the last
element returned by the iterator.
20
Using Iterator
ArrayList<String> list = new Arralist<String>();
list.add("ArrayList");
list.add(" and ");
list.add("Iterators");
String result = "";
for (Iterator<String> listIterator = list.iterator(); listIterator.hasNext(); )
{
result += listIterator.next();
}
stdout.println(result);
21
Using the For-Each Loop in Collections
ArrayList<String> list = new Arralist<String>();
list.add("ArrayList");
list.add(" and ");
list.add("for-each");
String result = "";
for (String element : list) {
result += element;
}
stdout.println(result);
22
Implementing Collection Class
23
Implement class Client
import java.util.*;
public class Client implements Iterable<BankAccount> {
/* Name of client */
private String name;
/* Collection of <code>BankAccounts</code>
objects.*/
private ArrayList<BankAccount> accounts;
24
Implement class Client
/**
* Constructs a <code>Client</code> object.
* <p>
* Creates an empty collection of bank accounts.
* </p>
*
* @param initialName the name of the client.
*/
public Client(String initialName) {
this.name = initialName;
this.accounts = new ArrayList<BankAccount>();
}
25
Implement class Client
/**
* Adds a bank account to this client.
*
* @param bankAccount the {@link BankAccount} object.
*/
public void addAccount(BankAccount bankAccount) {
this.accounts.add(bankAccount);
}
26
Implement class Client
/**
* Returns an iterator over the bank accounts of this client.
*
* return an {@link Iterator} over the bank accounts of this
*
client.
*/
public Iterator<BankAccount> iterator() {
return this.accounts.iterator();
}
27
Implement class Client
/**
* Returns the number of bank account of this client.
*
* @return the number of bank account of this client.
*/
public int getNumberOfAccounts() {
return this.accounts.size();
}
}
28
TestClient.java
public class TestClient {
private static PrintWriter stdOut = new PrintWriter(System.out, true);
private static PrintWriter stdErr = new PrintWriter(System.err, true);
public static void main(String[] args) {
BankAccount accountOne = new BankAccount();
BankAccount accountTwo = new BankAccount();
BankAccount accountThree = new BankAccount();
accountOne.deposit(1000.0);
accountTwo.deposit(2000.0);
accountThree.deposit(3000.0);
Client client= new Client("John Smith");
client.addAccount(accountOne);
client.addAccount(accountTwo);
client.addAccount(accountThree);
29
TestClient.java
double totalBalance = 0.0;
for (BankAccount account : client) {
totalBalance += account.getBalance();
}
if (totalBalance != 6000.0) {
stdErr.println("** Test failure");
}
stdOut.println("done");
}
}
30
ArrayList、Vector差异
一.同步性:Vector是线程安全的,也就是说是同步
的,而ArrayList是线程序不安全的,不是同步的
二.数据增长:当需要增长时,Vector默认增长为原来
一培,而ArrayList却是原来的一半
31
Class Diagram
32
Class Catalog
import java.util.*;
import java.io.*;
/**
* Maintains the information of a library catalog. Contains a
* collection of {@link CatalogItem} objects.
*
* @author author name
* @version 1.0.0
* @see CatalogItem
*/
public class Catalog implements Iterable<CatalogItem> {
/* Collection of <code>CatalogItem</code> objects.*/
private ArrayList<CatalogItem> items;
33
Class Catalog
/**
* Constructs an empty catalog.
*/
public Catalog() {
this.items = new ArrayList<CatalogItem>();
}
34
Class Catalog
/**
* Adds a {@link CatalogItem} object to this
catalog.
*
* @param catalogItem the {@link CatalogItem}
object.
*/
public void addItem(CatalogItem catalogItem) {
this.items.add(catalogItem);
}
35
Class Catalog
/**
* Returns an iterator over the items in this catalog.
*
* return an {@link Iterator}
*/
public Iterator<CatalogItem> iterator()
{
return this.items.iterator();
}
36
Class Catalog
/**
* Returns the {@link CatalogItem} object with the specified
* <code>code</code>.
*
* @param code the code of an item.
* @return The {@link CatalogItem} object with the specifed
*
code. Returns <code>null</code> if the object with
*
the code is not found.
*/
public CatalogItem getItem(String code) {
for (CatalogItem catalogItem : this.items) {
if (catalogItem.getCode().equals(code)) {
return catalogItem;
}
}
return null;
}
37
Class Catalog
/**
* Returns the number of items in the catalog.
*
* @return the number of {@link CatalogItem} objects in this
*
catalog
*/
public int getNumberOfItems() {
return this.items.size();
}
}
38
Class Diagram
39
Class BorrowerItems
import java.util.*;
import java.text.*;
/**
* Maintains a collection of {@link CatalogItems}
* assigned to a borrower.
*
* @author author name
* @version 1.0.0
* @see CatalogItem
*/
public class BorrowedItems implements Iterable<CatalogItem> {
/* Catalog items assigned to a borrower.*/
private ArrayList<CatalogItem> items;
40
Class BorrowerItems
/**
* Sets the collection of {@link CatalogItems} to empty.
*/
public BorrowedItems() {
this.items = new ArrayList<CatalogItem>();
}
41
Class BorrowerItems
/**
* Adds a {@link CatalogItem} object to this collection and
* sets the {@link CatalogItem} object as not available.
*
* @param item the {@link CatalogItem} object.
*/
public void addItem(CatalogItem catalogItem) {
this.items.add(catalogItem);
catalogItem.setAvailable(false);
}
42
Class BorrowerItems
/**
* Removes a {@link CatalogItem} object from this collection
* and sets the {@link CatalogItem} object as available.
*
* @param item the {@link CatalogItem} object.
*/
public void removeItem(CatalogItem catalogItem) {
this.items.removeElement(catalogItem);
catalogItem.setAvailable(true);
}
43
Class BorrowerItems
/**
* Returns an iterator over the borrowed items in this
* collection.
*
* return an {@link Iterator}
*/
public Iterator<CatalogItem> iterator() {
return this.items.iterator();
}
44
Class BorrowerItems
/**
* Returns the {@link CatalogItem} object with the specified
* <code>code</code>.
*
* @param code the code of an item.
* @return The {@link CatalogItem} object with the specifed
*
code. Returns <code>null</code> if the object with
*
the code is not found.
*/
public CatalogItem getItem(String code) {
for (CatalogItem catalogItem : this.items) {
if (catalogItem.getCode().equals(code)) {
return catalogItem; } }
return null;
}
45
Class BorrowerItems
/**
* Returns the number of borrowed items.
*
* @return the number of borrowed items.
*/
public int getNumberOfItems() {
return this.items.size();
}
}
46
Class Diagram
47
Class BorrowerDatabase
import java.util.*;
import java.text.*;
/**
* Maintains a collection of {@link Borrower} objects.
*
* @author author name
* @version 1.0.0
* @see Borrower
*/
public class BorrowerDatabase implements Iterable<Borrower> {
/* Collection of <code>Borrower</code> objects.*/
private ArrayList<Borrower> borrowers;
48
Class BorrowerDatabase
/**
* Constructs an empty collection of {@link Borrower}
* objects.
*/
public BorrowerDatabase() {
this.borrowers = new ArrayList<Borrower>();
}
49
Class BorrowerDatabase
/**
* Adds a {@link Borrower} object to this collection.
*
* @param borrower the {@link Borrower} object.
*/
public void addBorrower(Borrower borrower) {
this.borrowers.add(borrower);
}
50
Class BorrowerDatabase
/**
* Returns an iterator over the borrowers in this database.
*
* return an {@link Iterator}
*/
public Iterator<Borrower> iterator() {
return this.borrowers.iterator();
}
51
Class BorrowerDatabase
/**
* Returns the {@link Borrower} object with the specified
* <code>id</code>.
*
* @param code the id of the borrower.
* @return The {@link Borrower} object with the specifed id.
*
Returns <code>null</code> if the object with the
*
id is not found.
*/
public Borrower getBorrower(String id) {
for (Borrower borrower : this.borrowers) {
if (borrower.getId().equals(id)) {
return borrower;
}}
return null;
}
52
Class BorrowerDatabase
/**
* Returns the number of {@link Borrower} objects in this
* collection.
*
* @return the number of {@link Borrower} objects in this
*
collection.
*/
public int getNumberOfBorrowers() {
return this.borrowers.size();
}
}
53
Collection类继承关系
54