159'234 Lecture 10 - PowerPoint PPT Presentation

1 / 23
About This Presentation
Title:

159'234 Lecture 10

Description:

int) in class java.lang.String has been deprecated. key.getBytes( 0, key.length(), keyBytes, 0 ); Note: HashTable.java uses or overrides a deprecated API. ... – PowerPoint PPT presentation

Number of Views:35
Avg rating:3.0/5.0
Slides: 24
Provided by: ecal
Category:

less

Transcript and Presenter's Notes

Title: 159'234 Lecture 10


1
159.234 LECTURE
31
JAVA
  • Java Abstract Data Types
  • java.util package

2
From C to Java
Some important distinctions are
In Java, all executable statements must be
encapsulated in classes.
Java uses Object elements in lieu of template
classes
Java allows no external functions or variables.
Java uses references instead of pointers.
All arguments are passed by value.
In C, we write string s new string
In Java, its equivalent to String s new
String()
Java uses automatic garbage collection instead of
the delete operator.
3
From C to Java
4
From C to Java
5
From C to Java
6
From C to Java
7
From C to Java
8
Java Advanced Data Structures
  • java.util package
  • Use of abstract data types
  • Linked List example
  • HashTable example
  • Like the C STL - only more powerful and more
    extensive

9
Java Collections Framework
Collections
A collection is an object that contains other
objects
The contained objects are called the elements of
the collection.
The java.util package defines three general types
of collections
  • List
  • Set
  • Map

defined as interfaces that are extended and
implemented within a larger framework of
interfaces and classes in the java.util package.
JCF
Java implements each of the interfaces with
several different data structures
e.g. Array, linked linear structure, linked
binary search tree, etc.
10
Java Collections Framework
JCF
Fundamental Types in the JCF
List a collection containing an ordered
sequence of elements
Set a collection containing a mathematical set
of elements, with no duplication
Map a collection that maps keys into values
List, Set, and Map are subinterfaces of the
Collection interface. ListIterator is a
subinterface of the Iterator interface
11
Java Collections Framework
JCF
Data Structures used by the Concrete Classes in
JCF
Legacy classes Vector, Stack, Dictionary,
HashTable
subject to deprecation
The Vector and Stack classes have been superseded
by the ArrayList class.
The Dictionary and HashTable classes have been
superseded by the HashMap class.
12
  • java.util.Vector is a variable-sized array.
  • Vector has a default size.
  • can store any object type
  • when it reaches its capacity, the size is
    incremented by a set amount
  • provides accessor methods to search/add/delete
    elements.
  • java.util.HashTable implements efficient storage
  • stores elements according to their hashCode (a
    property of java.lang.Object inherited by all
    objects)
  • java.util package
  • A Java library containing useful functions for
    storing dynamic arrays and for storing arrays
    with efficient access
  • Unlike C STL generics, the Java containers
    can contain any Object

- all objects in Java descend from
java.lang.Object
13
The java.util.Collection INTERFACE
The Collection interface is the fundamental
supertype for all the List and Set types in Java.
public interface Collection public boolean
add(Object o) public boolean addAll(Collection
c) public voidclear() public boolean
contains(Object o) public boolean
containsAll(Collection c) public boolean
equals(Object o) public int hashCode() public
boolean isEmpty() public Iterator iterator()
public boolean remove(Object o) public boolean
removeAll(Collection c) public boolean
retainAll(Collection c) public int
size() public Object toArray() public
Object toArray(Object a)
Classification of Methods
  • Accessor methods
  • contains(),isEmpty(), size(), toArray()
  • Mutator methods
  • add(), clear(), remove(), retain()
  • Overrides of Object methods
  • equals(), hashCode()
  • Iterator
  • iterator()

14
The java.util.Collection INTERFACE
The Four Set-Theoretic Methods of the Collection
Interface
Remove all elements of y that are found in x.
Remove elements not found in both x and y.
Returns true if y is a subset of x
15
Testing an ArrayList Object
import java.util. public class
TestArrayList public static void main(String
args) Collection list new ArrayList()
list.add("US") list.add("CA")
list.add("FR") list.add("DE")
System.out.println("list " list)
System.out.println("list.contains(\"FR\") "
list.contains("FR")) System.out.println("list.c
ontains(\"GB\") " list.contains("GB"))
Object a list.toArray() System.out.println(
"after list.remove(\"FR\")")
list.remove("FR") System.out.println("list "
list) System.out.println("list.contains(\"FR\
") " list.contains("FR"))
System.out.println("list.size() "
list.size()) System.out.println("a2 "
a2)
Program Output
list US, CA, FR, DE list.contains("FR")
true list.contains("GB") false after
list.remove("FR") list US, CA,
DE list.contains("FR") false list.size()
3 a2 FR
The behaviour of the list variable is limited to
the methods that are declared in the Collection
interface.
toString() is invoked here
16
Java Collections Framework
Examples of Lists implemented by Java Linked
Lists and Vectors
Vector defines a list of objects that can be
accessed in random order by an index. It is like
an array of references to objects, except that
its size can grow or shrink, while the size of an
array is fixed. - easy to access any element in
random order (direct access), but is quite
tedious to add/delete elements in the middle of
the list
Linked Lists defines a list of objects, each
containing a data element plus a reference to the
next element in the list. - easy to add and
remove elements, but elements can only be
accessed sequentially (sequential access)
Both implement the List and ListIterator
interfaces, so they can be used in exactly the
same manner.
See VectorVsList.java
17
Testing the Vector and LinkList Objects
See VectorVsList.java
double temp
Object o new Vector()
Object o new LinkedList()
((List) o).add(new Double(temp))
Type-wrapper class to allow the primitive data
type double to be used with the List object.
ListIterator it ((List) o).listiterator()
double d it.next()
Program Output
d ((List) o).get(index)
Vector Time to add elements 0.09 Time to get
sequential elements 0.09 Time to get random
elements 0.0 LinkedList Time to add elements
0.05 Time to get sequential elements 0.05 Time
to get random elements 0.571
The results will differ significantly if you
compile and run using JBuilder.
Both LinkedList and Vector can be accessed using
identically the same statements because they both
support the List and ListIterator interfaces
18
  • public synchronized Linkable removeFromTail()
  • if (head null) return null
  • Linkable p head, q null, next
    head.getNext()
  • if (next null)
  • head null
  • return p
  • while((next p.getNext()) ! null)
  • q p
  • p next
  • q.setNext(null)
  • return p
  • public synchronized void remove(Linkable node)
  • if (head null) return
  • if (node.equals(head))
  • public class LinkedList
  • public interface Linkable
  • public Linkable getNext() //
    Returns next element in the list
  • public void setNext(Linkable node) // Sets
    the next element in the list
  • Linkable head // head of the linked list
  • public synchronized Linkable getHead()
  • return head
  • public synchronized void insertAtHead(Linkable
    node)
  • node.setNext(head)
  • head node
  • public synchronized void insertAtTail(Linkable
    node)

You may also implement your own class to be used
with a LinkedList object.
See LinkedList.java
19
  • public static class Test
  • static class LinkableInteger implements
    Linkable
  • int i // The data contained in
    the node
  • Linkable next // A reference to the next
    node in the list
  • public LinkableInteger(int i) this.i i
    // Constructor method
  • public Linkable getNext() return next
    // Part of Linkable
  • public void setNext(Linkable node) next
    node // Part of Linkable
  • public String toString() return i ""
    // For easy printing
  • public boolean equals(Object o)
    // For comparison
  • if (this o) return true
  • if (!(o instanceof LinkableInteger))
    return false
  • if (((LinkableInteger)o).i this.i)
    return true
  • return false
  • /
  • The test program. Insert some nodes,
    remove some nodes, then
  • print out all elements in the list. It
    should print out the
  • Linked List Example
  • linkable objects example
  • note filename mangling done for inner classes
  • gt java LinkedListTest
  • 4
  • 6
  • 3
  • 1
  • 5
  • gt

See LinkedList.java
20
HashTable Example
  • hashtable worked example code
  • note use of HashObject as data structure
  • note use of dedicated exception handler
  • integrated test method
  • order of tests important to avoid
    nullPointerException
  • use java.util.HashTable for real applications
  • evolution of the language - deprecation - see
    example

21
  • public void put( String key, Object data )
  • HashObject obj new HashObject()
  • obj.key key
  • obj.data data
  • obj.next null
  • bucketAdd( table, getBucket(hashCode(key)),
    obj)
  • count
  • if( count gt size rehashSize )
  • rehash()
  • public Object get( String key ) throws
    NoSuchKeyException
  • HashObject place table getBucket(
    hashCode(key) )
  • while( place ! null place.key.compareTo(ke
    y) ! 0 ) // note order
  • place place.next
  • if( place null )
  • //
  • // Hash table Example Program
  • //
  • class HashObject // data structure for holding
    list of key/value pairs
  • String key
  • Object data
  • HashObject next
  • class NoSuchKeyException extends Exception //
    exception handler
  • public NoSuchKeyException( String s )
  • super( s )
  • public NoSuchKeyException()
  • super()

22
  • public static void main( String args ) //
    main method for test code
  • HashTable table new HashTable()
  • for(int i 0 ilt5 i)
  • table.put("STRING " i, new Integer(i) )
  • for(int i10 igt0 i--)
  • try
  • System.out.println("KEY STRING " i
    " VALUE "
  • table.get("STRING " i ) )
  • catch( NoSuchKeyException e )
  • System.out.println(" Key Not Found "
    e.getMessage() )
  • // end of class HashTable
  • gtjavac -deprecation HashTable.java
  • HashTable.java61 Note The method void
    getBytes(int, int, byte,
  • private int getBucket( int hash )
  • return hash size
  • private void bucketAdd( HashObject table, int
    bucket, HashObject obj )
  • obj.next table bucket
  • tablebucket obj
  • private void rehash()
  • int newSize size capacityIncrement
  • HashObject newTable
  • HashObject tmp, obj
  • if( newSize 2 0 )
  • newSize
  • newTable new HashObjectnewSize
  • for(int i 0 ilt size i)
  • tmp tablei

23
Exercises
  • Browse the java.util package
  • Compare the methods for the various container
    classes
  • Consider which you would use to implement a
    Graph consisting of nodes and edges
  • How would you implement a Directed Graph where
    edges have a direction?

24
Summary
  • Java comes with a rich library of utilities and
    container classes
  • The containers can hold any Object
  • The API is growing
  • Track changes on the Java/Sun web sites
Write a Comment
User Comments (0)
About PowerShow.com