Dynamic Data Structures and Generics - PowerPoint PPT Presentation

1 / 64
About This Presentation
Title:

Dynamic Data Structures and Generics

Description:

A data structure is a construct used to organize data in a specific way. ... to trim to the current size. v.trimToSize(); to set the size. v.setSize(howMany) ... – PowerPoint PPT presentation

Number of Views:116
Avg rating:3.0/5.0
Slides: 65
Provided by: robertp6
Category:

less

Transcript and Presenter's Notes

Title: Dynamic Data Structures and Generics


1
Dynamic Data Structures and Generics
  • Chapter 10

2
Introduction
  • A data structure is a construct used to organize
    data in a specific way.
  • An array is a static data structure.
  • double t new double7 // size 7 is fixed
  • Dynamic data structures can grow and shrink while
    a program is running.
  • Vectors and linked data structures are dynamic.

3
Data Structure
  • Algorithms Data Structures Programs

Written by N. Wirth
4
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.

5
Introduction, cont.
  • Java 5.0 allows definitions with parameters for
    types.
  • These definitions are known as generics.

6
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, but
  • an array turns out to be too small or large
  • resizing of an array is expensive
  • the unused portion of the array is a waste

7
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.)

8
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.
  • When more capacity is needed, the system
    allocates more memory automatically.
  • If the initial capacity was sufficient, the code
    is more efficient.

9
Operations on Vector
  • to add an element to the end
  • 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)
  • to learn the size of the vector
  • int howMany v.size() // 0 to v.size()-1

ArrayIndexOutOfBoundsException
10
Operations contd
  • 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(postion)
  • to remove the first occurrence of an element
  • boolean done v.removeElement(Hello!)
  • to remove all elements
  • v.removeAllElements()

11
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 position v.indexOf(Hi, Mom!)
  • to learn the location of the first occurrence of
    an element at or after a position
  • int position v.indexOf(Hello, startFrom)

12
Searching a Vector, cont.
  • to learn the location of the last occurrence of
    an element
  • int position 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 first v.lastElement()

13
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()
  • to set the size
  • v.setSize(howMany)

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

15
  • VectorDemo

16
Vector Demonstration, cont.
17
Using Method clone
  • Creates an independent copy
  • return type of method clone is Object.
  • NOT the type of calling object
  • So, always use a correct type cast
  • otherV (VectorltStringgt)v.clone()
  • Vector otherV v.clone() //ILLEGAL

18
Using Method clone, cont.
  • Accessor methods should not return a private
    instance variable of type Vector.
  • the return value is a pointer that provides a way
    to access private data
  • same for array
  • 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.

19
Parameterized Classes
  • The class Vector is a parameterized class.
  • vectorltBase_Typegt v new VectorltBase_Typegt(20)
  • Its parameter, denoted Base_Type, can be replaced
    by any class type.

20
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.
  • 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.

21
A Linked List
  • Links, shown as arrows 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
  • Each node is an object of a class that has (at
    least) two instance variables
  • the data
  • the link.
  • A link instance variable with the value null
    indicates the last node.

22
  • class ListNode

getLink returns an instance variable which is a
reference to a private node, potentially
defeating the private restriction of the instance
variable.
23
  • class StringLinkedList

24
StringLinkedList
  • int length()
  • addANodeToStart(String addData)
  • delete HeadNode()
  • onList(String target)
  • ListNode Find(String target)
  • showList()

25
Moving Down a Linked List
ListNode position position head
26
Adding a Node at the Start
27
Removing the first Node from the list
  • Use deleteHeadNode ()

head head.getlink()
head.getlink() returns the reference to the
old second node,
28
Null Pointer Exception
  • The message NullPointerException indicates that
    access has been attempted using a class variable
    that names no object.
  • A NullPointerException does not need to be caught
    or declared in a throws clause.
  • Instead, it indicates that the code needs to be
    fixed.

29
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.
  • getLink is used only for StringLinkedList class,
    and it does not need to be seen outside it
  • This problem can be remedied by making class
    ListNode a private inner class of class
    StringLinkedList.

30
Inner Class
  • public class OuterClass
  • Declarations_of_OuterClass_Instance_Variables
  • Declarations_of_OuterClass_Methods
  • private class InnerClass
  • Declarations_of_InnerClass_Instance_Variab
    les
  • Declarations_of_InnerClass_Methods

31
  • class StringLinkedListSelfContained

32
  • class StringLinkedListSelfContained, cont.

33
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.
  • what we need
  • current the node on which we are working
  • previous in case we need to delete the current

34
Iterators
  • for (index 0 index lt a.length index)
  • process aindex
  • index is the iterator.

35
  • class StringLinkedListWithIterator

36
  • class StringLinkedListWithIterator, cont.

37
  • class StringLinkedListWithIterator, cont.

38
Advancing to the Next Node
39
Adding a Node
40
Deleting a Node
41
Exception Handling with Linked Lists
  • Occasionally, we do not want to end a program
    that uses a linked when something unusual
    happens.
  • In these rare cases, an exception can be thrown
    and handled appropriately.

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

43
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.

44
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
  • ...

45
Variations on a Linked List, cont.
46
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.

47
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.

48
Data Structures
Stack
Insertion and deletion at the same end
top
LIFO
49
Data Structures
Queue
Insertion and deletion at the different ends
head and tail
FIFO
50
Data Structures
Tree
51
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.

52
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.

53
Generic Basics, cont.
  • class SampleltTgt

54
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.

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

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

57
  • class LinkedListltEgt

58
  • class LinkedListltEgt, cont.

59
  • class GenericDemo

60
Programming Example A Generic Linked List, cont.
61
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.

62
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.

63
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

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