Java Data Structures (and Other Utility Classes) - PowerPoint PPT Presentation

1 / 30
About This Presentation
Title:

Java Data Structures (and Other Utility Classes)

Description:

Java Data Structures (and Other Utility Classes) CSE301 University of Sunderland Harry R. Erwin, PhD – PowerPoint PPT presentation

Number of Views:187
Avg rating:3.0/5.0
Slides: 31
Provided by: HarryE158
Category:

less

Transcript and Presenter's Notes

Title: Java Data Structures (and Other Utility Classes)


1
Java Data Structures (and Other Utility Classes)
  • CSE301
  • University of Sunderland
  • Harry R. Erwin, PhD

2
Programs DataAlgorithms
  • Even in object-oriented languages like Java!
  • You are expected to master the material on data
    structures and iterators.
  • Some general utility classes also discussed.
  • Read your key text!
  • Java in a Nutshell is an excellent reference.

3
java.lang.String
  • Not a Collection, but does hold Unicode
    characters.
  • Constant and of fixed length once created.
  • Supports the and operations to build up
    strings from components.
  • toString() converts an object into a String.
  • s.length() is the length.
  • The usual string operations from C and C have
    analogs in Java. Comparison is dictionary order.
  • Test questions! Read Flanagan!

4
java.util.Collection
  • The Collection interface represents a group or
    collection of objects.
  • It provides various methods that allow the
    collection to be manipulated effectively.
  • It provides an Iterator (next slide) for any
    specialization of Collection. This is a Good
    Thing.
  • Collections work with Objects. These must be
    tested for membership (using instanceof) before
    being typecast into their real class. Only then
    will class methods become available.
  • You use these classes to implement links with
    multiplicity in UML class diagrams.
  • Test questions!

5
java.util.Iterator
  • An Iterator is an interface for a collection that
    allows a program to review the contents of the
    collection.
  • Provides three methods
  • boolean hasNext() // true if there are more data
  • Object next() // gives the next object
  • void remove() // eliminates the most recent
    Object returned by next().
  • Sample idiom for accessing objects via an
    Iterator i
  • while(i.hasNext()) // test to see if done
  • Object o i.next() // get the next object
  • if(o instanceof ClassName) // test for
    membership
  • ClassName c (ClassName) o // typecast to
    ClassName
  • c.doYourThing(args) // doYourThing(args) is a
    member method
  • Test questions!

6
Why are Collections Important?
  • Although they dont bother teaching it here since
    it involves simple maths, the complexity of
    algorithms is very important.
  • Memory and disk capacity are growing much faster
    than CPU speed, so your programmes will be
    running on enormous data sets eventually. You
    want to avoid creating performance black holes.
  • Unless you design your algorithms to work with
    big data sets, you will not be holding a
    programming job for very long.

7
What is a Programmer to Do?
  • Use flexible, dynamically-allocated data instead
    of fixed-sized arrays. Arrays are almost
    guaranteed to be too small eventually.
  • Know your algorithms actual complexity.
  • Prefer to use linear or faster algorithms
    wherever possible. Avoid worse-than-linear
    algorithms.
  • Never use an exponential algorithm unless there
    is no other choice.
  • Test questions!

8
Linear, etc.
  • Constant-time means that it is unconcerned with
    the size of the collection.
  • Linear means that it is proportional to the size
    of the collection
  • Quadratic means that it is proportional to the
    square of the size of the collection
  • Exponential means that it is proportional to k
    (size of the collection) so that adding an
    element to the collection multiplies the run time
    of the method by k. As long as k is bigger than
    1.0, this is a bad thing.

9
Collections and Speed
  • Arrays and ArrayLists support constant-time
    access but linear-time insertion/deletion/search.
  • LinkedLists support constant-time insertion and
    removal and linear-time access and search.
  • Maps give you fast indexed access and linear
    unindexed search time.
  • Hash-based collections support near constant-time
    access, insertion, search, and removal.
  • Tree-based collections are a compromise between
    constant-time and linear-time access/search/
    insertion/deletion.
  • Test questions!

10
java.util.Set
  • An unordered Collection that contains no
    duplicates.
  • Sometimes useful in algorithms or in math.
  • The indices of a Map or database table form a
    Set. Hence you can Iterate over the index Set to
    access all Map or table values.
  • Implementations include
  • HashSet
  • LinkedHashSet
  • TreeSet
  • Test questions!

11
java.util.List
  • A linear collection in no specific order. Think
    array.
  • May have duplicates.
  • Can grow as required. Think dynamic array.
  • Implementations include
  • LinkedList
  • ArrayList (better in most ways than an array)
  • Vector
  • Use for queues, stacks, sorted queues.
  • Stores objects (and primitive types in Java 5)
  • Look at the method documentation!
  • Test questions!

12
java.util.Map
  • Contains ltKey,Valuegt pairs, both are Objects.
    Java 5 allows primitive types.
  • Keys must be unique, Values need not be.
  • Can grow and supports fast random access.
  • Can be used as a database table.
  • Implementations include
  • HashMap
  • LinkedHashMap
  • TreeMap
  • Hashtable
  • Look at the method documentation!
  • Test questions!

13
Static Classes
  • The following classes provide utility functions
    that would be provided by libraries in C or C
  • java.util.Arrays (sorting, searching,
    conversions, other useful operations)
  • java.util.Collections (sorting, searching, other
    useful operations, converting between collection
    types, making collections constantltsometimes
    very useful)
  • java.lang.Math (range limits, mathematical
    functions)
  • Know what they do and how to use them!
  • Test questions!

14
Events
  • Class EventObjectsuperclass for the events used
    by the Java GUI frameworks and JavaBeans.
  • Class EventListenerbase interface for the event
    model in Java. A null interface used as a tag.
  • These can be managed in queues and other
    collections.

15
Currency
  • Instances of this class represent currency.
  • Currency objects are created by passing a
    currency code (USD, EUR, UKP) to
    Currency.getInstance()

16
Date and Time
  • The Date class provides both dates and times in a
    system-independent way.
  • Most of the Date methods have been replaced by
    methods of the Calendar class.

17
Locale
  • Represents a political, geographical, or cultural
    region that needs specific formatting
    conventions.
  • Arcane, but important if you have to localize a
    program.

18
StringTokenizer
  • Given a string, it parses it into tokens.
  • Simplifies some text processing. Consider using
    to process input data.
  • Used by compilers and interpreters.
  • Actually is a stream (next lecture).

19
Random
  • Implements a (pseudo-)random number generator.
  • If you know what that is, you probably care.
  • Default seed is the current time, but you can
    provide your own seed for repeatability.

20
Sample Questions and Answers From Past Exams
  • Reference Data Types
  • Programming Classes
  • Collections

21
Reference Data Types
  • What is the syntax needed to declare (name) and
    create an instance of a class in Java?
  • Foo theFoo // names the instance
  • theFoo new Foo(arguments) // creates it

22
Reference Data Types
  • What is the syntax needed to declare (name) and
    create an instance of an array containing ten
    strings in Java?
  • String theArray // or
  • String theArray // either is valid
  • theArray new String10 // or
  • theArray "", "", "", "", "", "", "", "", "",
    "

23
Reference Data Types
  • Can you copy an instance of an interface to an
    Object safely? Justify your answer.
  • Yes, because all reference data types (class
    instances, interface instances, array instances)
    inherit from the class Object.

24
Programming Classes
  • Explain in detail what the keyword static means
    in a class definition.
  • A static element in a class definition is defined
    at the class level. This means that it is
    shared among all instances of the class. Note
    that static methods can only work with static
    elements.
  • I usually explain that each class has a class
    instance in addition to any individual
    instances. This is where the static elements
    live. They must be referred to using
    ClassName.elementName, rather than
    instance.elementName.

25
Programming Classes
  • Suppose you have a protected member field in a
    class. What methods in what classes can see it.
  • Methods in the class itself.
  • Methods in classes in the same package.
  • Methods in subclasses of the class in other
    packages.
  • Note, credit was implicitly given for answer 1
    if you answered 2.
  • One out of three was worth 3 two out of three
    was worth 7. If you gave incorrect answers in
    addition to correct answers, you lost a couple
    of marks.

26
Programming Classes
  • Suppose you have a final variable in a class
    method. What does that mean about the variable
    (in detail)?
  • It functions as a constant. Once given a value,
    it cannot be changed in the method. Note that
    since declaring and creating an instance of an
    object can be in separate statements, the
    variable can be initialized after it is declared.

27
Collections
  • Give an example of the correct use of an Iterator
    associated with a Collection c to print out the
    objects in the collection.
  • Iterator i c.iterator()
  • while(i.hasNext())
  • Object o i.next()
  • if(o!null)System.out.println(o)
  • // uses toString() method in Object class

28
Collections
  • Why is a Map not a Collection? Explain in detail.
  • A Collection interface represents a group or
    collection of objects. A Map interface represents
    a collection of mappings between key objects and
    value objects. The set of key objects must not
    contain any duplicates and should usually be
    immutable. A Map does not inherit from a
    Collection in Java, but its keys form a Set and
    its values form a Collection. To access its keys,
    use the keySet() method, and to access its
    values, use the values() method.

29
Collections
  • Suppose a Map m contains Integer values. Show how
    to compute the average of those values. Be
    suitably paranoid.
  • A Map must contain Integer values because the
    values in the map must be Objects, not primitive
    types. The values in a Map can be accessed as a
    Collection using the values() method, and an
    Iterator can be created based on that Collection
    to access each individual value.

30
Programming an Iterator
Iterator i (m.values()).iterator() double
total 0.0 long int count 0 while(i.hasNext()
) Object o i.next() if(o instanceof
Integer) int val ((Integer)o).intValue() to
tal val count double average
(countgt0?val/count0.0)
Write a Comment
User Comments (0)
About PowerShow.com