Title: Dynamic Data Structures and Generics
1Dynamic Data Structures and Generics
2Introduction
- 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.
3Data Structure
- Algorithms Data Structures Programs
Written by N. Wirth
4Introduction, 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.
5Introduction, cont.
- Java 5.0 allows definitions with parameters for
types. - These definitions are known as generics.
6Introduction 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
7Introduction 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.)
8Using 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.
9Operations 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
10Operations 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()
11Searching 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)
12Searching 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()
13Size 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)
14Copying and Equality Check
- to make a copy
- VectorltStringgt w v.clone()
- to test for equality
- boolean same v.equals(w)
15 16Vector Demonstration, cont.
17Using 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
18Using 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.
19Parameterized 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.
20Linked 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.
21A 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.
22getLink returns an instance variable which is a
reference to a private node, potentially
defeating the private restriction of the instance
variable.
23 24StringLinkedList
- int length()
- addANodeToStart(String addData)
- delete HeadNode()
- onList(String target)
- ListNode Find(String target)
- showList()
25Moving Down a Linked List
ListNode position position head
26Adding a Node at the Start
27Removing the first Node from the list
head head.getlink()
head.getlink() returns the reference to the
old second node,
28Null 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.
29Privacy 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.
30Inner 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.
33Iterators
- 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
34Iterators
- 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.
38Advancing to the Next Node
39Adding a Node
40Deleting a Node
41Exception 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.
42Exception Handling with Linked Lists, cont.
43Variations 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.
44Variations 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
- ...
45Variations on a Linked List, cont.
46Variations 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.
47Other 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.
48Data Structures
Stack
Insertion and deletion at the same end
top
LIFO
49Data Structures
Queue
Insertion and deletion at the different ends
head and tail
FIFO
50Data Structures
Tree
51Introduction 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.
52Generic 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.
53Generic Basics, cont.
54Generic 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.
55Generic 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)
56Generic Basics, cont.
- You cannot substitute a primitive type for a type
parameter. - You must instead use a class type.
57 58- class LinkedListltEgt, cont.
59 60Programming Example A Generic Linked List, cont.
61Limited 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.
62Limited 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.
63Summary
- 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
64Summary, cont.
- You have learned about iterators.
- You have learned about generics (parameters for
types).