Lists and the Collection Interface Review inheritance & collections

Click here to load reader

download Lists  and the Collection Interface Review inheritance & collections

of 73

description

Lists and the Collection Interface Review inheritance & collections. Objectives. Theory: To understand list, linked list To study the difference between single-, double-, and circular linked list data structures Implementation: List interface, ArrayList , LinkedList - PowerPoint PPT Presentation

Transcript of Lists and the Collection Interface Review inheritance & collections

Inheritance and Class Hierarchies

Lists and the Collection InterfaceReview inheritance & collectionsObjectives2Theory:To understand list, linked list To study the difference between single-, double-, and circular linked list data structuresImplementation:List interface, ArrayList, LinkedListReview Java inheritance and collection

3

4

5

6

7

Insert in the middle of Linkedlist8

BeforeAfter

Review question9______is a version of a linked list in which nodes can be navigated in the forward direction only.Doubly Linked ListSingly Linked ListCircular Linked ListAll of the above

Review question10______is a version of a linked list in which nodes can be navigated in forward direction only.

Doubly Linked ListSingly Linked List Circular Linked ListAll of the above

The List Interface and ArrayList Class11An array is an indexed structure: can select its elements in arbitrary order using a subscript valueElements may be accessed in sequence using a loop that increments the subscriptYou cannotIncrease or decrease the lengthAdd an element at a specified position without shifting the other elements to make roomRemove an element at a specified position without shifting other elements to fill in the resulting gapImplementation: List interface12

Implementation: List interface13boolean add(Object o) void clear() boolean contains(Object o) Object get(int index) int indexOf(Object o) boolean isEmpty() Iterator iterator() int lastIndexOf(Object o) ListIterator listIterator() ListIterator listIterator(int index) Object remove(int index) boolean remove(Object o) int size() Object[] toArray() Implementation: List Interface14Allowed operations on the List interface include:Finding a specified targetAdding an element to either endRemoving an item from either endTraversing the list structure without a subscriptAn array provides the ability to store primitive-type data whereas the List classes all store references to ObjectsReview question15A method that does not alter a linked list but simply looks at it to determine whether its empty, is referred as ________methodisClear()isNull()isEmpty()isZero()

Review question16A method that does not alter a linked list but simply looks at it to determine whether its empty, is referred as ________methodisClear()isNull()isEmpty()isZero()

Array-based list implementation.ArrayList Class17

Array-based list implementation.ArrayList Class18Simplest class that implements the List interfaceImprovement over an array objectUsed when a programmer wants to add new elements to the end of a list but still needs the capability to access the elements stored in the list in arbitrary order

ArrayList Class19

Specification of the ArrayList Class20

Application of ArrayList21The ArrayList gives you additional capability beyond what an array providesArrayList stores items of type Object and can thus store an object of any classYou cannot store values of the primitive types directly but must instead use wrapper classesWhen an object is stored in an ArrayList, the programmer must remember the original typeSingle-Linked Lists and Double-Linked Lists22ArrayList: add and remove methods operate in linear time because they require a loop to shift elements in the underlying arrayLinked list overcomes this by providing ability to add or remove items anywhere in the list in constant timeEach element (node) in a linked list stores information and a link to the next, and optionally previous, nodeA List Node23

A List Node24A node contains a data item and one or more linksA link is a reference to a nodeA node is generally defined inside of another class, making it an inner classThe details of a node should be kept privateDouble-Linked Lists25Limitations of a single-linked list include:Can insert a node only after a referenced nodeCan remove a node only if we have a reference to its predecessor nodeCan traverse the list only in the forward directionAbove limitations removed by adding a reference in each node to the previous node (double-linked list)Double-Linked Lists26

Double-Linked ListsChapter 4: Lists and the Collection Interface27

Inserting into a Double-Linked List28

Removing from a Double-Linked List29

Circular Lists30Circular-linked list: link the last node of a double-linked list to the first node and the first to the lastAdvantage: can traverse in forward or reverse direction even after you have passed the last or first nodeCan visit all the list elements from any starting pointCan never fall off the end of a listDisadvantage: infinite loop!Circular Lists Continued31

LinkedList Class32Part of the Java APIImplements the List interface using a double-linked list

The Iterator Interface33The interface Iterator is defined as part of API package java.utilThe List interface declares the method iterator, which returns an Iterator object that will iterate over the elements of that listAn Iterator does not refer to or point to a particular object at any given timeIterator InterfaceChapter 3: Inheritance and Class Hierarchies34

The ListIterator Interface35Iterator limitationsCan only traverse the List in the forward directionProvides only a remove methodMust advance an iterator using your own loop if starting position is not at the beginning of the listListIterator is an extension of the Iterator interface for overcoming the above limitationsIterator should be thought of as being positioned between elements of the linked list

The ListIterator Interface (continued)36

Comparison of Iterator and ListIterator37ListIterator is a subinterface of Iterator; classes that implement ListIterator provide all the capabilities of bothIterator interface requires fewer methods and can be used to iterate over more general data structuresIterator is required by the Collection interface, whereas the ListIterator is required only by the List interfaceConversion between a ListIterator and an Index38ListIterator has the methods nextIndex and previousIndex, which return the index values associated with the items that would be returned by a call to the next or previous methodsThe LinkedList class has the method listIterator(int index) Returns a ListIterator whose next call to next will return the item at position indexThe Collection Hierarchy39Both the ArrayList and LinkedList represent a collection of objects that can be referenced by means of an indexThe Collection interface specifies a subset of the methods specified in the List interfaceCollection interface is the root of the collection hierarchyTwo branches: one rooted by the List interface and the other by the Set interfaceThe Collection Hierarchy (continued)40

Common Features of Collections41Collection interface specifies a set of common methodsFundamental features include:Collections grow as neededCollections hold references to objectsCollections have at least two constructors

Inheritance and Class Hierarchies43Introduction to Inheritance and Class HierarchiesPopularity of OOP is that it enables programmers to reuse previously written code saved as classesAll Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classesInheritance in OOP is analogous to inheritance in humansInheritance and hierarchical organization allow you to capture the idea that one thing may be a refinement or extension of another

44Introduction to Inheritance and Class Hierarchies (continued)

45Is-a Versus Has-a RelationshipsOne misuse of inheritance is confusing the has-a relationship with the is-a relationshipThe has-a relationship means that one class has the second class as an attributeWe can combine is-a and has-a relationshipsThe keyword extends specifies that one class is a subclass of another46A Superclass and a SubclassConsider two classes: Computer and LaptopA laptop is a kind of computer and is therefore a subclass of computer

47Initializing Data Fields in a Subclass and the No-Parameter ConstructorPrivate data fields belonging to a base class must be initialized by invoking the base classs constructor with the appropriate parametersIf the execution of any constructor in a subclass does not invoke a superclass constructor, Java automatically invokes the no-parameter constructor for the superclassInitializes that part of the object inherited from the superclass before the subclass starts to initialize its part of the object48Protected Visibility for Superclass Data FieldsPrivate data fields are not accessible to derived classesProtected visibility allows data fields to be accessed either by the class defining it or any subclassIn general, it is better to use private visibility because subclasses may be written by different programmers and it is always good practice to restrict and control access to the superclass data fields49Method OverridingIf a derived class has a method found within its base class, that method will override the base classs methodThe keyword super can be used to gain access to superclass methods overridden by the base classA subclass method must have the same return type as the corresponding superclass method50Method OverloadingMethod overloading: having multiple methods with the same name but different signatures in a classConstructors are often overloadedExample:MyClass(int inputA, int inputB)MyClass(float inputA, float inputB)

51PolymorphismA variable of a superclass type can reference an object of a subclass typePolymorphism means many forms or many shapesPolymorphism allows the JVM to determine which method to invoke at run timeAt compile time, the Java compiler cant determine what type of object a superclass may reference but it is known at run time52Abstract Classes, Assignment, and Casting in a HierarchyAn interface can declare methods but does not provide an implementation of those methodsMethods declared in an interface are called abstract methodsAn abstract class can have abstract methods, data fields, and concrete methodsAbstract class differs from a concrete class in thatAn abstract class cannot be instantiatedAn abstract class can declare abstract methods, which must be implemented in its subclasses53Abstract Classes and InterfacesLike an interface, an abstract class cant be instantiatedAn abstract class can have constructors to initialize its data fields when a new subclass is createdSubclass uses super() to call the constructorMay implement an interface but it doesnt have to define all of the methods declared in the interfaceImplementation is left to its subclasses54Abstract Class Number and the Java Wrapper Classes

55Summary of Features of Actual Classes, Abstract Classes, and Interfaces

56Class Object, Casting and CloningObject is the root of the class hierarchy; every class has Object as a superclassAll classes inherit the methods defined in class Object but may be overridden

57The Method toStringYou should always override the toString method if you want to represent an objects stateIf you do not override it, the toString method for class Object will return a stringjust not the string you want or are expecting58Operations Determined by Type of Reference VariableA variable can reference an object whose type is a subclass of the variable typeThe type of reference, not the type of the object referenced, determines what operations can be performedJava is a strongly typed language so the compiler always verifies that the type of the expression being assigned is compatible with the variable type

59Casting in a Class HierarchyJava provides casting to enable us to process one object referenced by one type through a reference variable of its actual typeCasting does not change the object referenced; it creates an anonymous reference to that objectDowncast: cast a higher type to a lower typeThe instanceof operator can guard against ClassCastException errorsYou can downcast an interface reference to the specific implementation type 60The Method Object.equalsThe Object.equals method has a parameter of type ObjectCompares two objects to determine whether they are equalYou must override the equals method if you want to be able to compare two objects of a class

61CloningThe purpose of cloning in object-oriented programming is analogous to cloning in biologyCreate an independent copy of an objectInitially, both objects will store the same informationYou can change one object without affecting the other

62The Shallow Copy Problem

63The Object.clone methodJava provides the Object.clone method to help solve the shallow copy problemThe initial copy is a shallow copy as the current objects data fields are copiedTo make a deep copy, you must create cloned copies of all components by invoking their respective clone methods

64Multiple Inheritance, Multiple Interfaces, and DelegationMultiple inheritance: the ability to extend more than one classMultiple inheritance is a language feature that is difficult to implement and can lead to ambiguityTherefore, Java does not allow a class to extend more than one class

65Using Multiple Interfaces to Emulate Multiple InheritanceIf we define two interfaces, a class can implement bothMultiple interfaces emulate multiple inheritance

66Implementing Reuse Through DelegationYou can reduce duplication of modifications and reduce problems associated with version control through a technique known as delegationIn delegation, a method of one class accomplishes an operation by delegating it to a method of another class

Chapter 3: Inheritance and Class Hierarchies67PackagesThe Java API is organized into packagesThe package to which a class belongs is declared by the first statement in the file in which the class is defined using the keyword package followed by the package nameAll classes in the same package are stored in the same directory or folderAll the classes in one folder must declare themselves to be in the same packageClasses that are not part of a package may access only public members of classes in the packageChapter 3: Inheritance and Class Hierarchies68The No-Package-Declared Environment and Package VisibilityThere exists a default packageFiles that do specify a package are considered part of the default packageIf you dont declare packages, all of your packages belong to the same, default packagePackage visibility sits between private and protectedClasses, data fields, and methods with package visibility are accessible to all other methods of the same package but are not accessible to methods outside of the packageClasses, data fields, and methods that are declared protected are visible to all members of the package69Visibility Supports EncapsulationThe rules for visibility control how encapsulation occurs in a Java programPrivate visibility is for members of a class that should not be accessible to anyone but the class, not even the classes that extend itPackage visibility allows the developer of a library to shield classes and class members from classes outside the packageUse of protected visibility allows the package developer to give control to other programmers who want to extend classes in the package70Visibility Supports Encapsulation (continued)

71A Shape Class Hierarchy

72A Shape Class Hierarchy (continued)

73A Shape Class Hierarchy (continued)