程序代写 ICT373: Software Architectures

Topic 3: Advanced Java –collections,
streams, persistence Sub Topic 1: Collections
ICT373: Software Architectures

Copyright By PowCoder代写 加微信 powcoder

• Java overview • Objects
• Java revision
• O-O design and The Unified Modelling Language (UML)

• Java Collections
• Java Exception Handling

Objectives
• Explain the Java Collections Framework.
• Describe the use of data structures like collections in Java and the use of iterators.
• Explain the use of generics and enhanced for loop in Java.
• Explain how exceptions are handled in Java.

JAVA Collections

Collections: Arrays
• A collection is a data structure that represents a group of objects, known as its elements.
• Actually, it is an object—that can hold references to other objects.
• Usually, collections contain references to objects that are all of the
same type (or subtype).
• Arrays are efficient ways to store and randomly access collections of objects.
• They are efficiently implemented.
• Bound checking is done during storage and recall.
• They can be returned by a method: an array is an object.
• They can hold primitives.
• But they have to be fixed in size.
• Therefore, the Java SE and other Java libraries supply other sorts of collection classes.

Java Collections Framework (1/3)
• A framework is a set of classes that form the basis for building advanced functionality. It contains superclasses with useful functionality, policies and mechanisms.
• The user of a framework writes subclasses to extend the functionality without having to reinvent the basic mechanisms. Eg, Swing is a framework for user interfaces.
• The Java collections framework (JCF) is a hierarchy of classes, abstract classes, interfaces and algorithms that implement commonly usable collection data structures.
• There are two fundamental interfaces for Java collections (JCF):
• Collection – defines a value for each item in the data
structure;
• Map – defines a pair of items, key-value, for each element/node in the data structure.

Java Collections Framework (2/3)
• java.util.Collection is a root interface in the collections hierarchy from which the List, Queue and Set interfaces are derived. It declares the add(), remove(), toArray() and contains() method for a collection.
• java.util.List interface is an ordered collection that can contain duplicate elements. In addition to the methods inherited from Collection, List provides (eg, add, remove, get, set) methods for manipulating elements via their indices, manipulating a specified range of elements (eg, addAll, removeAll, subList), searching for elements and obtaining a ListIterator to access the elements. Interface List is implemented by several classes, including ArrayList, LinkedList and Vector.
• java.util.Queue interface – typically, a FIFO collection that models a waiting line.

Java Collections Framework (3/3)
• java.util.Set interface – a collection that does not contain duplicates.
• java.util.Map interface that associates keys to values and cannot contain duplicate keys. Interface Map is implemented by classes HashMap, TreeMap and LinkedHashMap.
• All collections have an iterator that goes through all of the elements in the collection.

Collection classes (1/3)
• The following abstract classes supply many of the routine implementation of the interface methods: AbstractCollection, AbstractList, AbstractSequentialList, AbstractSet, AbstractQueue, and AbstractMap.
• The Java library provides the following concrete classes: ArrayList, LinkedList, ArrayQueue, PriorityQueue, HashSet, TreeSet, HashMap, and TreeMap.
• There is also a number of “legacy” container classes available before there was a collections framework: Vector, Stack, Hashtable, and Properties.

Collection classes (2/3)
• Thus there is a whole hierarchy of useful collection classes and interfaces available for use. Eg, one branch is
interface Collection |
+–interface List |
+–java.util.ArrayList
(Class ArrayList implements interface List which extends interface Collection)

Collection classes (3/3)
• The abstract classes and interfaces allow the user to make their own versions conform to the standard ways of use. Create a collection using a concrete class but then pass around a more abstract reference: this allows maximum potential for future changes.
• There are algorithms in these classes for binary search, reversing, sorting etc. There are constructors and methods for converting to and from Arrays.
• There is also a class Arrays (in java.util package) which contains static methods for doing useful things to arrays, eg binarySearch(), equals(), fill(), and sort().

Objects Only
• Collections of Marsupials and collections of lists of addresses, for example, should have methods (eg, elementAt) with different argument and return types.
• In earlier versions of Java, it is not possible to write code that can implement a generic collection type, such as a Stack, which will work for all types of contained objects.
• In C++, this problem is solved using parameterized types or templates.
• Java does not have templates. Java solves the problem by having collections which only hold Objects.
• Since every class inherits from Object, this means that every reference type (i.e. not primitive) of object can be put in a collection.

Objects Only
• primitives must be wrapped (eg, ints converted to Integers) before being collected
• Other objects must be downcast if you want to regain type information after they come out of a collection.
• Recall that downcasting can cause problems: incorrect downcasting causes run-time errors. Take care to note the types of collected objects, or use RTTI= run-time type identification (see later).

Generic Types
• A new feature of J2SE 5.0 is generics which allow definitions that include parameters for types.
• This enables designing of methods/classes with common functionality that can be used with multiple data types.
• Generic methods enable programmers to specify a set of related methods with a single method declaration. Eg, we may write a generic method for displaying array elements, then invoke the method with Integer arrays, Double arrays, Character arrays, and so on.

Generics: an example

Generic class
• Generic classes enable programmers to specify a set of related types with a single class definition. Eg, we might write a single generic stack class to manipulate a stack of objects, and then use it to process a stack of Integers, a stack of Doubles, a stack of Strings, and so on.
• The following example uses the JDK1.4 Collections API library: ArrayList list = new ArrayList();
list.add(0, new Integer(25));
int total = ((Integer)list.get(0)).intValue();
• The above example with the JDK1.5 generified Collections API: ArrayList list = new ArrayList(); list.add(0, new Integer(25));
int total = list.get(0).intValue();

Iterators (1)
• An object that allows a program to step through a collection of
objects and do some action on each one is called an iterator.
• Eg, for arrays, an index variable can be used as an iterator, with the action of going to the next thing in the list being something like: index++;
• With all collection classes there is a need to be able to extract and examine the elements one at a time.
• To gain access to the internal workings of a collection class, an iterator class is usually defined as an inner class.
• In Java, collections can produce an Iterator via their iterator() method. Clients can then use hasNext(), next() and remove() methods.

Iterators (2)
• Suppose we have an ArrayList a (for example).
• To get an iterator for a …
Iterator it = a.iterator();
• Then it is ready to return the first element. To get the first or
subsequent elements …
x = it.next();
• To test for the end (i.e., if there are any more objects) … if (it.hasNext()) …
• To remove the last element returned by the iterator … it.remove(); // remove() is an optional operation.
• You can have several iterators going at once.

Iterator: example

Exceptions

Exceptions
Another important Java class hierarchy deals with exceptions: objects allowing unusual situations to be handled without disrupting the normal code.
The syntax for exception handling is roughly
We try to execute some code.
One of several possible exceptions might be thrown at some point. Then execution is halted and resumed at a later place designed to catch and deal with that type of exception.
The finally block (if present) will execute whether or not an exception is thrown in the try block.

Throwing an exception
• When the values of variables are discovered to be unacceptable for current processing to continue and the local code is not the right place to deal with the problem then an exception should be thrown as follows:
throw new TypeOfException(“optional string”);
• The type of exception can be a built-in or user defined one.

Catching an Exception
• If the throwing code is inside a try block then the JVM starts at the inner- most such block and examines the following exception handling blocks (indicated by the catch keyword) in order.
• If the exception (which was thrown) matches the type of error being caught then that block is used. Matching works hierarchically, so general catchers can catch lots of types of exception. Eg,
catch (Exception id) will catch all exceptions.
• The handler block code can make use of the string message in the
exception object via id.getMessage()
• If the JVM gets to the end of a method with an unmatched exception then it goes back to the method of which called that method to see whether the calling point was in a try block.
• This continues from nested try blocks outwards and all the way back through the stack of method calls.
• Thus the programmer can arrange for the exception to be handled at the right level.

Exception Specification
• The code for any methods you write should declare (for the benefit of any clients) any types of exceptions which might be thrown in your method but not handled there. In that case the client (user of your class) has to handle them.
• Do so as follows:
void f () throws badName { …
if name.equals(“fred”)
throw new badName(“fred”);
• The compiler will actually check that you make such a declaration and your code won’t compile if you miss any potential exceptions.
• However, one class of common exceptions called RunTimeExceptions does not need to be declared. This class includes null references being called, array bounds being exceeded etc.

Creating your own exceptions
• Need to add your own new classes of exception to the hierarchy. To make use of all the benefits of the built-in exception handling procedures you need to inherit from an existing class. Eg,
class MyException extends Exception {  public MyException() {}
 public MyException(String msg){
 super(msg);
Note the two constructors, one relying on the automatic calling of the base- class default constructor, the other handing over to the Exception(String msg) constructor.
• By carefully constructing your hierarchy of exceptions you can make sure that exceptions are handled at appropriate places in your code.

throw vs try-catch

• Java collections
• Java exception handling

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com