Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lists and the Collection Interface Review inheritance & collections.

Similar presentations


Presentation on theme: "Lists and the Collection Interface Review inheritance & collections."— Presentation transcript:

1 Lists and the Collection Interface Review inheritance & collections

2 Objectives 2 Theory: To understand list, linked list To study the difference between single-, double-, and circular linked list data structures Implementation: List interface, ArrayList, LinkedList Review Java inheritance and collection

3 3

4 4

5 5

6 6

7 7

8 Insert in the middle of Linkedlist 8 Before After

9 Review question 9 ______is a version of a linked list in which nodes can be navigated in the forward direction only. a. Doubly Linked List b. Singly Linked List c. Circular Linked List d. All of the above

10 Review question 10 ______is a version of a linked list in which nodes can be navigated in forward direction only. a. Doubly Linked List b. Singly Linked List c. Circular Linked List d. All of the above

11 The List Interface and ArrayList Class 11 An array is an indexed structure: can select its elements in arbitrary order using a subscript value Elements may be accessed in sequence using a loop that increments the subscript You cannot Increase or decrease the length Add an element at a specified position without shifting the other elements to make room Remove an element at a specified position without shifting other elements to fill in the resulting gap

12 Implementation: List interface 12

13 Implementation: List interface 13 boolean 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()

14 Implementation: List Interface 14 Allowed operations on the List interface include: Finding a specified target Adding an element to either end Removing an item from either end Traversing the list structure without a subscript An array provides the ability to store primitive-type data whereas the List classes all store references to Objects

15 Review question 15 A method that does not alter a linked list but simply looks at it to determine whether it’s empty, is referred as ________method a. isClear() b. isNull() c. isEmpty() d. isZero()

16 Review question 16 A method that does not alter a linked list but simply looks at it to determine whether it’s empty, is referred as ________method a. isClear() b. isNull() c. isEmpty() d. isZero()

17 Array-based list implementation. ArrayList Class 17

18 Array-based list implementation. ArrayList Class 18 Simplest class that implements the List interface Improvement over an array object Used 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

19 ArrayList Class 19

20 Specification of the ArrayList Class 20

21 Application of ArrayList 21 The ArrayList gives you additional capability beyond what an array provides ArrayList stores items of type Object and can thus store an object of any class You cannot store values of the primitive types directly but must instead use wrapper classes When an object is stored in an ArrayList, the programmer must remember the original type

22 Single-Linked Lists and Double-Linked Lists 22 ArrayList: add and remove methods operate in linear time because they require a loop to shift elements in the underlying array Linked list overcomes this by providing ability to add or remove items anywhere in the list in constant time Each element (node) in a linked list stores information and a link to the next, and optionally previous, node

23 A List Node 23

24 A List Node 24 A node contains a data item and one or more links A link is a reference to a node A node is generally defined inside of another class, making it an inner class The details of a node should be kept private

25 Double-Linked Lists 25 Limitations of a single-linked list include: Can insert a node only after a referenced node Can remove a node only if we have a reference to its predecessor node Can traverse the list only in the forward direction Above limitations removed by adding a reference in each node to the previous node (double-linked list)

26 Double-Linked Lists 26

27 Double-Linked Lists Chapter 4: Lists and the Collection Interface 27

28 Inserting into a Double-Linked List 28

29 Removing from a Double-Linked List 29

30 Circular Lists 30 Circular-linked list: link the last node of a double-linked list to the first node and the first to the last Advantage: can traverse in forward or reverse direction even after you have passed the last or first node Can visit all the list elements from any starting point Can never fall off the end of a list Disadvantage: infinite loop!

31 Circular Lists Continued 31

32 LinkedList Class 32 Part of the Java API Implements the List interface using a double-linked list

33 The Iterator Interface 33 The interface Iterator is defined as part of API package java.util The List interface declares the method iterator, which returns an Iterator object that will iterate over the elements of that list An Iterator does not refer to or point to a particular object at any given time

34 Iterator Interface Chapter 3: Inheritance and Class Hierarchies 34

35 The ListIterator Interface 35 Iterator limitations Can only traverse the List in the forward direction Provides only a remove method Must advance an iterator using your own loop if starting position is not at the beginning of the list ListIterator is an extension of the Iterator interface for overcoming the above limitations Iterator should be thought of as being positioned between elements of the linked list

36 The ListIterator Interface (continued) 36

37 Comparison of Iterator and ListIterator 37 ListIterator is a subinterface of Iterator; classes that implement ListIterator provide all the capabilities of both Iterator interface requires fewer methods and can be used to iterate over more general data structures Iterator is required by the Collection interface, whereas the ListIterator is required only by the List interface

38 Conversion between a ListIterator and an Index 38 ListIterator 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 methods The LinkedList class has the method listIterator(int index) Returns a ListIterator whose next call to next will return the item at position index

39 The Collection Hierarchy 39 Both the ArrayList and LinkedList represent a collection of objects that can be referenced by means of an index The Collection interface specifies a subset of the methods specified in the List interface Collection interface is the root of the collection hierarchy Two branches: one rooted by the List interface and the other by the Set interface

40 The Collection Hierarchy (continued) 40

41 Common Features of Collections 41 Collection interface specifies a set of common methods Fundamental features include: Collections grow as needed Collections hold references to objects Collections have at least two constructors

42 Inheritance and Class Hierarchies

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

44 44 Introduction to Inheritance and Class Hierarchies (continued)

45 45 Is-a Versus Has-a Relationships One misuse of inheritance is confusing the has-a relationship with the is-a relationship The has-a relationship means that one class has the second class as an attribute We can combine is-a and has-a relationships The keyword extends specifies that one class is a subclass of another

46 46 A Superclass and a Subclass Consider two classes: Computer and Laptop A laptop is a kind of computer and is therefore a subclass of computer

47 47 Initializing Data Fields in a Subclass and the No-Parameter Constructor Private data fields belonging to a base class must be initialized by invoking the base class’s constructor with the appropriate parameters If the execution of any constructor in a subclass does not invoke a superclass constructor, Java automatically invokes the no-parameter constructor for the superclass Initializes that part of the object inherited from the superclass before the subclass starts to initialize its part of the object

48 48 Protected Visibility for Superclass Data Fields Private data fields are not accessible to derived classes Protected visibility allows data fields to be accessed either by the class defining it or any subclass In 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 fields

49 49 Method Overriding If a derived class has a method found within its base class, that method will override the base class’s method The keyword super can be used to gain access to superclass methods overridden by the base class A subclass method must have the same return type as the corresponding superclass method

50 50 Method Overloading Method overloading: having multiple methods with the same name but different signatures in a class Constructors are often overloaded Example: MyClass(int inputA, int inputB) MyClass(float inputA, float inputB)

51 51 Polymorphism A variable of a superclass type can reference an object of a subclass type Polymorphism means many forms or many shapes Polymorphism allows the JVM to determine which method to invoke at run time At compile time, the Java compiler can’t determine what type of object a superclass may reference but it is known at run time

52 52 Abstract Classes, Assignment, and Casting in a Hierarchy An interface can declare methods but does not provide an implementation of those methods Methods declared in an interface are called abstract methods An abstract class can have abstract methods, data fields, and concrete methods Abstract class differs from a concrete class in that An abstract class cannot be instantiated An abstract class can declare abstract methods, which must be implemented in its subclasses

53 53 Abstract Classes and Interfaces Like an interface, an abstract class can’t be instantiated An abstract class can have constructors to initialize its data fields when a new subclass is created Subclass uses super(…) to call the constructor May implement an interface but it doesn’t have to define all of the methods declared in the interface Implementation is left to its subclasses

54 54 Abstract Class Number and the Java Wrapper Classes

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

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

57 57 The Method toString You should always override the toString method if you want to represent an object’s state If you do not override it, the toString method for class Object will return a string…just not the string you want or are expecting

58 58 Operations Determined by Type of Reference Variable A variable can reference an object whose type is a subclass of the variable type The type of reference, not the type of the object referenced, determines what operations can be performed Java is a strongly typed language so the compiler always verifies that the type of the expression being assigned is compatible with the variable type

59 59 Casting in a Class Hierarchy Java provides casting to enable us to process one object referenced by one type through a reference variable of its actual type Casting does not change the object referenced; it creates an anonymous reference to that object Downcast: cast a higher type to a lower type The instanceof operator can guard against ClassCastException errors You can downcast an interface reference to the specific implementation type

60 60 The Method Object.equals The Object.equals method has a parameter of type Object Compares two objects to determine whether they are equal You must override the equals method if you want to be able to compare two objects of a class

61 61 Cloning The purpose of cloning in object-oriented programming is analogous to cloning in biology Create an independent copy of an object Initially, both objects will store the same information You can change one object without affecting the other

62 62 The Shallow Copy Problem

63 63 The Object.clone method Java provides the Object.clone method to help solve the shallow copy problem The initial copy is a shallow copy as the current object’s data fields are copied To make a deep copy, you must create cloned copies of all components by invoking their respective clone methods

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

65 65 Using Multiple Interfaces to Emulate Multiple Inheritance If we define two interfaces, a class can implement both Multiple interfaces emulate multiple inheritance

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

67 Chapter 3: Inheritance and Class Hierarchies 67 Packages The Java API is organized into packages The 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 name All classes in the same package are stored in the same directory or folder All the classes in one folder must declare themselves to be in the same package Classes that are not part of a package may access only public members of classes in the package

68 Chapter 3: Inheritance and Class Hierarchies 68 The No-Package-Declared Environment and Package Visibility There exists a default package Files that do specify a package are considered part of the default package If you don’t declare packages, all of your packages belong to the same, default package Package visibility sits between private and protected Classes, 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 package Classes, data fields, and methods that are declared protected are visible to all members of the package

69 69 Visibility Supports Encapsulation The rules for visibility control how encapsulation occurs in a Java program Private visibility is for members of a class that should not be accessible to anyone but the class, not even the classes that extend it Package visibility allows the developer of a library to shield classes and class members from classes outside the package Use of protected visibility allows the package developer to give control to other programmers who want to extend classes in the package

70 70 Visibility Supports Encapsulation (continued)

71 71 A Shape Class Hierarchy

72 72 A Shape Class Hierarchy (continued)

73 73 A Shape Class Hierarchy (continued)


Download ppt "Lists and the Collection Interface Review inheritance & collections."

Similar presentations


Ads by Google