Dynamic Data Structures and Generics - PowerPoint PPT Presentation

About This Presentation
Title:

Dynamic Data Structures and Generics

Description:

Dynamic Data Structures and Generics Chapter 10 – PowerPoint PPT presentation

Number of Views:112
Avg rating:3.0/5.0
Slides: 59
Provided by: Rober1204
Category:

less

Transcript and Presenter's Notes

Title: Dynamic Data Structures and Generics


1
Dynamic Data Structures and Generics
  • Chapter 10

2
Objectives
  • become familiar with vectors
  • learn about linked data structures in Java
  • learn how to manipulate linked lists
  • learn to use inner classes in defining linked
    data structures
  • learn about iterators
  • learn about generics (parameters for types)

3
Outline
  • Vectors
  • Linked Data Structures
  • Introduction to Generics
  • (optional) Graphics Supplement

4
Introduction
  • A data structure is a construct used to organize
    data in a specific way.
  • An array is a static data structure.
  • Dynamic data structures can grow and shrink while
    a program is running.
  • Vectors and linked data structures are dynamic.

5
Introduction, cont.
  • Vectors are similar to arrays, but offer more
    flexibility.
  • The linked list is a simple but useful linked
    data structure that makes use of inner classes.
  • An inner class is a class definition within
    another class definition.

6
Introduction, cont.
  • Java 5.0 allows definitions with parameters for
    types.
  • These definitions are known as generics.
  • int scores new int100
  • scores new int200
  • Does NOT add 100 new locations to scores! It
    creates a new array of 200 locations and the old
    array becomes garbage ?

7
Vectors Outline
  • Introduction to Vectors
  • Using Vectors
  • Parameterized Classes and Generics

8
Introduction to Vectors
  • We can think of vectors as arrays that grow and
    shrink while a program is running.
  • At the time an array is created, its length is
    fixed.
  • Sometimes an array turns out to be too small for
    its intended use.
  • Sometimes an array turns out to be too large for
    its intended use, but the unused portion of the
    array is not available for other purposes.

9
Introduction to Vectors, cont.
  • Vectors serve the same purposes as arrays, but
    can change in length while a program is running.
  • This added flexibility comes at a price
  • Vectors are less efficient than arrays.
  • The base type of a vector must be a class type
    rather than a primitive type. (Automatic boxing
    and unboxing make this requirement less
    significant than it used to be.)

10
Using Vectors
  • The definition of class Vector must be imported.
  • import java.util.
  • to create and name a vector
  • VectorltStringgt v new VectorltStringgt(20)
  • The vector v stores objects of class String and
    has an initial capacity of 20.

11
Using Vectors, cont.
  • When more capacity is needed, the system
    allocates more memory automatically.
  • If the initial capacity was sufficient, the code
    is more efficient.
  • In this example, the base type is type String.
  • Any class can be used as the base type.
  • But, wrapper classes MUST be used for primitive
    types.

12
Creating and Naming a Vector
  • syntax
  • VectorltBase_Typegt v1 new
  • VectorltBase_Typegt()// capacity10, doubles
  • VectorltBase_Typegt v2 new
  • VectorltBase_Typegt(n)// capacityn, doubles
  • VectorltBase_Typegt v3 new
  • VectorltBase_Typegt(n,p)
    //capacityn, increases by p

13
Adding, Getting, and Setting Values
  • to add an element
  • v.addElement(Hello!)
  • to get the value of an element
  • String temp v.elementAt(index)
  • to change the value of an existing element
  • v.setElementAt(Hi, Mom!, index)

14
Size and Indices
  • to learn the size of the vector
  • int howMany v.size()
  • The indices range from 0 to v.size()-1.

15
Inserting and Removing Values
  • to insert an element
  • v.insertElementAt(Good-bye, position)
  • elements at index position or higher move to
    index positions greater by one.
  • to remove an element from a position
  • v.removeElementAt(position)

16
Inserting and Removing Values, cont.
  • to remove the first occurrence of an element
  • v.removeElement(Hello!)
  • to remove element at index i
  • v.removeElementAt(i)
  • to remove all elements
  • v.removeAllElements()

17
Searching a Vector
  • to learn if an element is in the vector
  • boolean found v.contains(Good-bye)
  • to learn the location of the first occurrence of
    an element
  • int location v.indexOf(Hi, Mom!)
  • to learn the location of the first occurrence of
    an element at or after a position
  • int location v.indexOf(Hello, position)

18
Searching a Vector, cont.
  • to learn the location of the last occurrence of
    an element
  • int location
  • v.lastIndexOf(Hi, Mom!)
  • to learn the value of the first element
  • String first v.firstElement()
  • to learn the value of the last element
  • String last v.lastElement()

19
Size and Capacity
  • to learn if the vector is empty
  • boolean none v.isEmpty()
  • to learn the current capacity
  • int howBig v.capacity()
  • to make room for more elements
  • v.ensureCapacity(moreElements)
  • to trim to the current size
  • v.trimToSize()

20
Size and Capacity, cont.
  • to set the size
  • v.setSize(howMany)

21
Copying and Determining Equality
  • to make a copy
  • VectorltStringgt w v.clone()
  • to test for equality
  • boolean same v.equals(w)

22
Vector Demonstration
  • class VectorDemo

23
Vector Demonstration, cont.
24
Using Method clone
  • When used with a vector, the assignment statement
    creates another reference to the same vector.
  • To make a copy of a vector, use
  • otherV (VectorltStringgt)v.clone()
  • using a correct type cast.
  • On the other hand
  • Vector otherV v.clone() //ILLEGAL
  • will produce an error message.

25
Using Method clone, cont.
  • Accessor methods should not return a private
    instance variable of type Vector.
  • Accessor methods should return a copy of the
    vector, not the private instance vector itself.
  • Method clone can be used to produce a copy of the
    private instance vector.

26
Using Method clone, cont.
  • However, the return type of method clone is
    Object.
  • Hence, the appropriate form is
  • public VectorltStringgt getVector()
  • return (VectorltStringgt)v.clone()
  • Any objects stored in the vector also must have
    appropriate accessor methods.

27
Parameterized Classes and Generics
  • The class Vector is a parameterized class.
  • Its parameter, denoted Base_Type, can be replaced
    by any class type.
  • Java 5.0 allows definitions, called generic
    definitions or simply generics, with parameters
    for types.

28
Newer Collection Classes
  • A new group of classes implement the Collection
    interface.
  • These classes are known as collection classes.
  • The Vector definition has been retrofitted to be
    a collection class.

29
Linked Data Structures Outline
  • Linked Lists
  • Inner Classes
  • Node Inner Classes
  • Iterators
  • Exception Handling with Linked Lists
  • Variations on a Linked List
  • Other Linked Data Structures

30
Introduction to Linked Data Structures
  • A linked data structure is a collection of
    objects (called nodes), each containing data and
    a (potential) reference to (at least) one other
    node.

31
Linked Lists
  • The predefined LinkedList class is part of the
    java.util package.
  • Nevertheless, to learn how linked data
    structures work, well construct a simplified
    example of a linked list.

32
Linked Lists, cont.
33
Linked Lists, cont.
  • Links, shown as arrows in the previous diagram,
    are implemented as references and are instance
    variables of the node type.
  • The reference marked head is a variable of the
    node type which provides access to the first node
    in the linked list, but is not itself one of the
    nodes.

34
Linked Lists, cont.
  • Each node is an object of a class that has (at
    least) two instance variables
  • the data
  • the link.

35
Linked Lists, cont.
  • class ListNode

36
Detecting the Last Node
  • There must be means for detecting the last node.
  • A link instance variable with the value null
    indicates the last node.
  • A reference to the linked list with the value
    null indicates an empty linked list.
  • The value of the link instance variable is tested
    using .

37
A Linked List of Strings
  • class StringLinkedList

38
Moving Down a Linked List
39
Adding a Node at the Start
40
A Linked List Demonstration
  • class LinkedListDemo

41
A Linked List Demonstration, cont.
42
Null Pointer Exception
  • The message NullPointerException indicates that
    access has been attempted using a class variable
    that names no object.
  • A reference value of null means that no object is
    named by the reference.
  • A NullPointerException does not need to be caught
    or declared in a throws clause.
  • Instead, it indicates that the code needs to be
    fixed.

43
Privacy Leaks
  • A method such as getLink in class ListNode
    returns an instance variable which is a reference
    to a node, potentially defeating the private
    restriction of the instance variable.

44
Privacy Leaks, cont.
  • class ListNode

45
Privacy Leaks, cont.
  • This problem can be remedied by making class
    ListNode a private inner class of class
    StringLinkedList.

46
Privacy Leaks, cont.
  • A method such as getData in class ListNode (page
    754) does not create a privacy leak because,
    unlike almost any other class, class String has
    no methods that change the value of the string
    without changing the reference.
  • Method Find (page ???) does not create a privacy
    leak because it is a private method.

47
Privacy Leaks, cont.
  • class ListNode

48
Inner Classes
  • An inner class is a class defined within another
    class.

49
Defining an Inner Class
  • public class OuterClass
  • OuterClass_Instance_Variables
  • OuterClass_Methods
  • private class InnerClass
  • InnerClass_Instance_Variables
  • InnerClass_Methods

50
Access to Members
  • The inner and outer classes methods have access
    to each others methods and instance variables,
    even when they are declared private.

51
Node Inner Classes
  • By making the node class an inner class, data
    structure classes become self-contained.
  • Further, the accessor and mutator methods of the
    inner class can be eliminated since instance
    variables of an inner class are accessible
    directly.

52
Node Inner Classes, cont.
  • class StringLinkedListSelfContained

53
Node Inner Classes, cont.
  • class StringLinkedListSelfContained, cont.

54
Iterators
  • With a collection of objects, such as the nodes
    of a linked list, we often need to step through
    all the objects to perform some action on each
    object.
  • An iterator allows us to step through a
    collection of objects.

55
Iterators, cont.
  • The loop control variable of a for loop functions
    as an iterator for an array.
  • for (int i 0 i lt a.length, i)
  • process ai

56
Iterators, cont.
  • method arrayCopy()

57
Iterators, cont.
  • Similarly, an instance variable capable of
    referencing a node, can serve the same purpose as
    the loop control variable in a for loop.
  • Another instance variable capable of referencing
    a node can follow behind to provide access to
    the previous node.

58
Iterators, cont.
  • class StringLinkedListWithIterator

59
Iterators, cont.
  • class StringLinkedListWithIterator, cont.

60
Iterators, cont.
  • class StringLinkedListWithIterator, cont.

61
Advancing to the Next Node
62
Adding a Node
63
Deleting a Node
64
A Linked List Can Be Its Own Iterator
  • Often we want the iterator of a linked list to be
    an object of some sort.
  • The same linked-list object can be used as the
    linked list and as the iterator.

65
Internal and External Iterators
  • An iterator defined within a linked-list class is
    an internal iterator.
  • When the elements of a linked list are copied
    into an array and iterated using the loop control
    variable of the array, the loop control variable
    is an external iterator because the iterator is
    outside the linked list.

66
Exception Handling with Linked Lists
  • Occasionally, we do not want to end a program
    that uses a linked list when something unusual
    happens.
  • In these rare cases, an exception can be thrown
    and handled appropriately.

67
Exception Handling with Linked Lists, cont.
  • method goToNext

68
Exception Handling with Linked Lists, cont.
  • Class LinkedListException

69
Variations on a Linked List
  • A reference to the last node in a linked list can
    be useful.
  • public ListNode head
  • public ListNode tail
  • A linked list can contain (or reference) any kind
    of data.

70
Variations on a Linked List, cont.
  • A linked list can contain different kinds of
    objects
  • private class ListNode
  • private Object data
  • private ListNode link
  • ...

71
Variations on a Linked List, cont.
  • An additional reference can be added to reference
    the previous node, producing a doubly-linked
    list.
  • private class ListNode
  • private Object data
  • private ListNode next
  • private ListNode previous
  • ...

72
Variations on a Linked List, cont.
73
Variations on a Linked List, cont.
  • The last node in a singly-linked list can
    reference the first node, producing a
    circularly-linked list.
  • The last node in a doubly-linked list can
    reference the first node with its next reference,
    and the first node can reference the last node
    with its previous reference, producing a
    doubly-circularly-linked list.

74
Other Linked Data Structures
  • Many colleges and universities offer a course
    devoted entirely to the study of data structures.
  • Typically, a data structure can be implemented by
    linking its elements together.
  • Example data structures include stacks, queues,
    deques, trees, binary trees, graphs, and directed
    graphs.

75
Introduction to Generics
  • Java 5.0 allows definitions, called generics,
    that include parameters for types.
  • Generics can be subtle and full of pitfalls.
  • We provide an introduction to generics.
  • Serious programming with generics is presented in
    more advanced texts.

76
Generic Basics
  • Classes and methods can have a type parameter.
  • Any class type can be substituted for the type
    parameter, producing a specific class type or
    method.

77
Generic Basics, cont.
  • class SampleltTgt

78
Generic Basics, cont.
  • A class definition with a type parameter is
    stored in a file and compiled just like any other
    class.
  • When used in code a class type must be specified
    so that it can be substituted for the type
    parameter.

79
Generic Basics, cont.
  • example
  • SampleltStringgt o1 new SampleltStringgt()
  • o1.setData(Hello)
  • SampleltSpeciesgt o2 new SampleltSpeciesgt()
  • Species s new Species()
  • ltcode to set the data for object sgt
  • o2.setData(s)

80
Generic Basics, cont.
  • You cannot substitute a primitive type for a type
    parameter.
  • You must instead use a class type.

81
Programming Example A Generic Linked List
  • class LinkedListltEgt

82
Programming Example A Generic Linked List, cont.
  • class LinkedListltEgt, cont.

83
Programming Example A Generic Linked List, cont.
  • class GenericDemo

84
Programming Example A Generic Linked List, cont.
85
Generic Constructor
  • The class name in a parameterized class
    definition has a type parameter attached.
  • But, a generic constructor name has no type
    parameter and the type parameter is not used in
    the heading of the constructor definition.
  • public LinkedList()
  • not
  • public LinkedListltegt() // ILLEGAL

86
Limited Use of the Type Parameter
  • Within the definition of a parameterized class
    definition, there are places where a type name is
    allowed, but a type parameter is not allowed.
  • Type parameters cannot be used in simple
    expressions that use new to create a new object.

87
Limited Use of the Type Parameter
  • examples
  • T object new T() // ILLEGAL
  • T a new T10 // ILLEGAL
  • In both cases, the first T is legal, but the
    second T is illegal.

88
Summary
  • You have become familiar with vectors.
  • You have learned about linked data structures in
    Java.
  • You have learned how to manipulate linked lists.
  • You have learned to use inner classes in defining
    linked data structures

89
Summary, cont.
  • You have learned about iterators.
  • You have learned about generics (parameters for
    types).
Write a Comment
User Comments (0)
About PowerShow.com