Скачать презентацию
Идет загрузка презентации. Пожалуйста, подождите
Презентация была опубликована 9 лет назад пользователемТимофей Селиверстов
1 Object-Oriented Programme 1 SSD3: Object-Oriented Programming and Design
2 Object-Oriented Programme Implementing Classes 2.2 Collections 2.3 Advanced Class Design Assessments Exam 2 Unit 2. Class Implementation
3 Object-Oriented Programme 3 Collections Collections Arrays ArrayList and Iterators Implementing the Collections of the Library System Assessments Practical Quiz 6 Practical Quiz 7 Multiple-Choice Quiz 4 Exercise 4
4 Object-Oriented Programme Arrays Arrays Declaring and Using Arrays Example Using Arrays
5 Object-Oriented Programme 5 Arrays 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.
6 Object-Oriented Programme 6 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. null Each will remain null until an array object is created. (In Java, arrays are implemented as objects.)
7 Object-Oriented Programme 7 create an array object To create an array object, use the new operator, followed by the type of the elements and the arrays 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 0 the elements of the array names are initialized to null. null
8 Object-Oriented Programme 8 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; }
9 Object-Oriented Programme 9 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
10 Object-Oriented Programme 10 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
11 Object-Oriented Programme 11 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: 1. it is used as the array index and 2. it is used to calculate the value of each array element. 3. values.length is part of the loop termination condition.
12 Object-Oriented Programme 12 Example Using Arrays Sample code ( Dictionary.java)
13 Object-Oriented Programme 13 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.
14 Object-Oriented Programme ArrayList and Iterators The ArrayList Class Iterators Using the For-Each Loop in Collections Implementing Collection Classes
15 Object-Oriented Programme 15 The ArrayList Class The class java.util.ArrayList implements a collection of objects that can grow to accommodate new items when the collection is full. The objects in the ArrayList can be accessed using an integer index.
16 Object-Oriented Programme 16 some of the 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).
17 Object-Oriented Programme 17 some of the methods defined in class ArrayList 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).
18 Object-Oriented Programme 18 Class ArrayList holds references to objects Class ArrayList holds references to objects of a particular data type. (not the object themselves) E.g., following segment of code creates a list of employees adds three employees to the list ArrayList employees = new ArrayList (); employees.add(new Employee("John Smith")); employees.add(new Employee("Mary Williams")); employees.add(new Employee("Peter Jefferson")); Employee firstEmployee = employees.get(0);
19 Object-Oriented Programme 19 collections can only hold object references collections can only hold object references rather than primitive types, primitive types must be placed in a wrapper object before they can be placed in a collection Integer in the case of int. E.g., illustrates how to use an ArrayList of integers: ArrayList numbers = new ArrayList (); numbers.add(1); // int num = numbers.get(0); Java has the ability to automatically box and unbox primitive data types, reducing the complexity to add and access primitive data types in the collections.
20 Object-Oriented Programme 20 Iterators Iterators The ArrayList method iterator() returns a java.util.Iterator object over the elements of the ArrayList. 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.
21 Object-Oriented Programme 21 The class java.util.Iterator methods boolean hasNext(). HasSth...() 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. This method throws the exception IllegalStateException, if the next() has not been called, or the remove() has already been called after the last call to the next().
22 Object-Oriented Programme 22 Sample code code concatenates the strings in a collection and then displays the result: "ArrayList and Iterators". ArrayList list = new Arralist (); list.add("ArrayList"); list.add(" and "); list.add("Iterators"); String result = ""; for (Iterator listIterator = list.iterator(); listIterator.hasNext(); ) { result += listIterator.next(); } stdout.println(result);
23 Object-Oriented Programme 23 Sample Source code(DictionaryWithArrayList.java) The words of the dictionary are stored in an ArrayList collection. line 87 addWord() calls the ArrayList method add to add a word to the dictionary. line 100 hasWord() calls the ArrayList contains() to determine if the specified word is part of the dictionary. line 115 getStartsWith() uses an iterator to traverse the dictionary and returns an ArrayList with all words in the dictionary that start with the specified prefix. line 142 removeStartsWith() calls the Iterator method remove to remove a word from the dictionary.
24 Object-Oriented Programme 24 Using the For-Each Loop in Collections The for-each loop provides a simple way to iterate through the elements of a collection. In the for-each loop, you should specify the collection to iterate through, and a variable to access each element. code uses a for-each loop to concatenates the strings in a collection and then displays the result: "ArrayList and for- each". ArrayList list = new Arralist (); list.add("ArrayList"); list.add(" and "); list.add("for-each"); String result = ""; for (String element : list) { result += element; } stdout.println(result);
25 Object-Oriented Programme 25 note The for-each loop can be used only on those classes that implement the interface java.util.Iterable. An interface is a Java programming language construct that defines a group of methods that are implemented by a class. OOP To implement the interface Iterable, the class must include an implements clause in the class declaration, and declare the method iterator(). public class MyCollection implements Iterable {... public Iterator iterator() {... } The iterator() must return an Iterator object which is used to obtain the elements stored in the collection in a sequential order.
26 Object-Oriented Programme 26 Implementing Collection Classes a collection class models a one-to-many relationship. The one-to-many relationship can be implemented using an ArrayList to store the various instances in the collection. In addition, the class provides a set of methods to handle the collection.
27 Object-Oriented Programme 27 example the following class diagram represents a client with a collection of BankAccount instances.
28 Object-Oriented Programme 28 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, TestClient.java)
29 Object-Oriented Programme 29 NOTE The class Client uses an ArrayList to implement the collection of BankAccount objects. The class implements the interface Iterable provides the addAccount() to add a BankAccount object in the collection, and provides the iterator() to access the BankAccount objects stored in the collection.
30 Object-Oriented Programme Implementing the Collections of the Library System Library System Collection Classes Class Catalog Class BorrowedItems Class BorrowerDatabase Complete Library System
31 Object-Oriented Programme 31 Library System Collection Classes
32 Object-Oriented Programme 32 classes use collections The following classes use collections: Catalog BorrowedItems BorrowerDatabase
33 Object-Oriented Programme 33 Class Catalog The class Catalog uses a collection of CatalogItem instances. Instance variables: items. A ArrayList 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)
34 Object-Oriented Programme 34 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 ArrayList 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)
35 Object-Oriented Programme 35 Class BorrowerDatabase The class BorrowerDatabase models a database of borrowers. It uses a collection of Borrower instances. Instance variables: borrowers. A ArrayList 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)
36 Object-Oriented Programme 36 Complete Library System The following files implement the other classes in the library system: Book.java Recording.java CatalogItem.java Borrower.java LibrarySystem.java
Еще похожие презентации в нашем архиве:
© 2024 MyShared Inc.
All rights reserved.