31.java collections framework

Upload: nguyen-lap

Post on 03-Jun-2018

241 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 31.Java Collections Framework

    1/62

    Java Collections Framework

    24 April 2013 OSU CSE 1

  • 8/12/2019 31.Java Collections Framework

    2/62

    Overview

    The Java Collections Framework (JCF)is a group of interfaces and classes similar

    to the OSU CSE components

    The similarities will become clearly evidentfrom examples

    See Java libraries package java.util There are some important differences, too,

    however, that deserve mention (at the

    end)

    24 April 2013 OSU CSE 2

  • 8/12/2019 31.Java Collections Framework

    3/62

    Overview of Interfaces

    24 April 2013 OSU CSE 3

    Set List Queue

    Collection

    Sorted-Set

    Sorted-Map

    Iterable

    Deque

    Navigable-Set

    Map

    Navigable-Map

  • 8/12/2019 31.Java Collections Framework

    4/62

    Overview of Interfaces

    24 April 2013 OSU CSE 4

    Set List Queue

    Collection

    Sorted-

    Set

    Sorted-Map

    Iterable

    Deque

    Navigable-Set

    Map

    Navigable-

    Map

    Note: Mapdoes notextend Collection;

    but it is a collection.

  • 8/12/2019 31.Java Collections Framework

    5/62

    Overview of Interfaces

    24 April 2013 OSU CSE 5

    Set List Queue

    Collection

    Sorted-

    Set

    Sorted-Map

    Iterable

    Deque

    Navigable-Set

    Map

    Navigable-

    Map

    Iterableis in java.lang

    (because of its intimateconnection to for-each loops),

    but Iteratoris in java.util.

  • 8/12/2019 31.Java Collections Framework

    6/62

    Overview of Interfaces

    24 April 2013 OSU CSE 6

    Set List Queue

    Collection

    Sorted-

    Set

    Sorted-Map

    Iterable

    Deque

    Navigable-Set

    Map

    Navigable-

    Map

    Subsequent slidesdiscuss only certain

    interfaces.

  • 8/12/2019 31.Java Collections Framework

    7/62

    The CollectionInterface

    Essentially a finite multiset of E No direct/efficient way to ask how many

    copies of a given element there are

    Two interesting methods to create arrays ofthe elements

    Many methods (including add, remove,clear) are optional

    24 April 2013 OSU CSE 7

  • 8/12/2019 31.Java Collections Framework

    8/62

    The SetInterface

    Essentially a finite set of E No removeAnyor similar method, so you

    must use iteratorto iterate over a Set

    Recall (from Iterator): The behavior of aniterator is unspecified if the underlying

    collection is modified while the iteration is in

    progress [except using Iterator.remove]. Many methods (including add, remove,clear) are optional

    24 April 2013 OSU CSE 8

  • 8/12/2019 31.Java Collections Framework

    9/62

    The ListInterface

    Essentially a string of EAccess by position (similar to Sequence

    from OSU CSE components)

    Many methods (including add, remove,clear) are optional

    Two interesting additional features: Sublist views of a ListA special two-way ListIterator

    24 April 2013 OSU CSE 9

  • 8/12/2019 31.Java Collections Framework

    10/62

    The ListInterface

    Essentially a string of EAccess by position (similar to Sequence

    from OSU CSE components)

    Many methods (including add, remove,clear) are optional

    Two interesting additional features: Sublist views of a ListA special two-way ListIterator

    24 April 2013 OSU CSE 10

    How do you move forwardand backward through a List

    from OSU CSE components?

  • 8/12/2019 31.Java Collections Framework

    11/62

    The QueueInterface

    Essentially a string of EAccess at ends (similar to Queuefrom

    OSU CSE components)

    Here, addand removeare notoptionaladdis similar to enqueuefor OSU CSE

    components Queue

    removeis similar to dequeue Curious names for other methods, e.g.,offer, peek, poll

    24 April 2013 OSU CSE 11

  • 8/12/2019 31.Java Collections Framework

    12/62

    The MapInterface

    Essentially a finite set of (K,V)with the function property

    No removeAnyor similar method, so youmust use iterator(somewhat indirectly)to iterate over a Map

    Many methods (including put, remove,clear) are optional

    Like List, a Mapsupports views of itselements

    24 April 2013 OSU CSE 12

  • 8/12/2019 31.Java Collections Framework

    13/62

    Views in the JCF

    A viewis a subcollection of a collection Not a copyof some of the elements, but rather

    a collection within a collectionthat is

    manipulated in place

    Views for Map: Keys: Set keySet() Values: Collection values() Pairs: Set entrySet()

    24 April 2013 OSU CSE 13

  • 8/12/2019 31.Java Collections Framework

    14/62

    Views in the JCF

    A viewis a subcollection of a collection Not a copyof some of the elements, but rather

    a collection within a collectionthat is

    manipulated in place

    Views for Map: Keys: Set keySet() Values: Collection values() Pairs: Set entrySet()

    24 April 2013 OSU CSE 14

    Map.Entryin the JCF is

    very similar to Map.Pairin the OSU CSE components.

  • 8/12/2019 31.Java Collections Framework

    15/62

    Example: Map m

    24 April 2013 OSU CSE 15

    Code Statem = {("PB", 99),

    ("BK", 42),

    ("SA", 42)}

    Set s =

    m.keySet();

    m = {("PB", 99),

    ("BK", 42),("SA", 42)}

    s = {"SA", "BK",

    "PB"}

  • 8/12/2019 31.Java Collections Framework

    16/62

    Example: Map m

    24 April 2013 OSU CSE 16

    Code Statem = {("PB", 99),

    ("BK", 42),

    ("SA", 42)}

    Set s =

    m.keySet();

    m = {("PB", 99),

    ("BK", 42),("SA", 42)}

    s = {"SA", "BK",

    "PB"}

    Note all the aliases here!There is no problem in this case

    because Stringis immutable,

    but consider the potential

    problems if it were not.

  • 8/12/2019 31.Java Collections Framework

    17/62

    24 April 2013 OSU CSE 17

    Code Statem = {("PB", 99),

    ("BK", 42),

    ("SA", 42)}

    Collection c =

    m.values();

    m = {("PB", 99),

    ("BK", 42),("SA", 42)}

    c = {42, 99, 42}

    Example: Map m

  • 8/12/2019 31.Java Collections Framework

    18/62

    24 April 2013 OSU CSE 18

    Code State

    m = {("PB", 99),

    ("BK", 42)}

    Set s =

    m.entrySet();

    m = {("PB", 99),

    ("BK", 42)}s = {("BK", 42),

    ("PB", 99)}

    Example: Map m

  • 8/12/2019 31.Java Collections Framework

    19/62

    View Backed By Collection

    A view is backed by the underlyingcollection, which means that if the view is

    modified then the underlying (backing)

    collection is also modified, and vice versa

    See Javadoc for supported modifications Be especially careful when iterating over a

    view or a collection and trying to modify it

    24 April 2013 OSU CSE 19

  • 8/12/2019 31.Java Collections Framework

    20/62

    Example: List s

    24 April 2013 OSU CSE 20

    Code State

    s =

    s.subList(1,3).clear();

    s =

  • 8/12/2019 31.Java Collections Framework

    21/62

    24 April 2013 OSU CSE 21

    Code State

    m = {("PB", 99),

    ("BK", 42),

    ("SA", 42)}

    m.values().remove(42);

    m = {("PB", 99),

    ("SA", 42)}

    Example: Map m

  • 8/12/2019 31.Java Collections Framework

    22/62

    24 April 2013 OSU CSE 22

    Code State

    m = {("PB", 99),

    ("BK", 42),

    ("SA", 42)}

    m.values().remove(42);

    m = {("PB", 99),

    ("SA", 42)}

    Example: Map m

    Because removeforCollection(assuming it is

    available for m.values!)

    removes one copy, we do not

    know which pair remains in m.

  • 8/12/2019 31.Java Collections Framework

    23/62

  • 8/12/2019 31.Java Collections Framework

    24/62

    Could removeCause Trouble?

    The object (dynamic) type ofm.values()in the above code might be

    an implementation of Listor of Queue

    But not of Set; why not? The removebeing called is optional if

    the object type of m.values()is a List

    implementation, but not if it is a Queue How can the client know what interface it

    implements?

    24 April 2013 OSU CSE 24

    The informal Javadoc for the valuesmethod says:The collection supports element removal, which

    removes the corresponding mapping from the map, via

    the Iterator.remove, Collection.remove,

    removeAll, retainAlland clearoperations. It does

    not support the addor addAlloperations.

  • 8/12/2019 31.Java Collections Framework

    25/62

    Could removeCause Trouble?

    The object (dynamic) type ofm.values()in the above code might be

    an implementation of Listor of Queue

    But not of Set; why not? The removebeing called is optional if

    the object type of m.values()is a List

    implementation, but not if it is a Queue How can the client know what interface it

    implements?

    24 April 2013 OSU CSE 25

    Since valuesreturns an object whose dynamic typesupports removebut not add, apparently that return

    type implements a fictitious (phantom?) interface that is

    stronger than Collection, but different than all of Set,

    List, and Queue.

  • 8/12/2019 31.Java Collections Framework

    26/62

    Iterating Over a Map

    Because Mapdoes notextend Iterable,but Collection(hence Set) does

    extend Iterable, you can (only) iterate

    over a Mapusing one of its three views: Keys: Set keySet() Values: Collection values() Pairs: Set entrySet()

    24 April 2013 OSU CSE 26

  • 8/12/2019 31.Java Collections Framework

    27/62

    Overview of CollectionClasses

    24 April 2013 OSU CSE 27

    Collection

    Iterable

    Abstract-Collection

    There are no classes

    that directly and fullyimplement

    Collection.

    Object

  • 8/12/2019 31.Java Collections Framework

    28/62

    AbstractCollection

    Has code for many methods (shared, andpossibly overridden, by all later

    implementations of Collection) :

    addremoveclear...

    24 April 2013 OSU CSE 28

  • 8/12/2019 31.Java Collections Framework

    29/62

    AbstractCollection

    Has code for many methods (shared, andpossibly overridden, by all later

    implementations of Collection) :

    addremoveclear...

    24 April 2013 OSU CSE 29

    This methods implementation here, forexample, always throws an

    UnsupportedOperationException.

  • 8/12/2019 31.Java Collections Framework

    30/62

    Overview of SetClasses

    24 April 2013 OSU CSE 30

    Set

    HashSet

    AbstractSet

    TreeSet

    Collection

    Iterable

    Abstract-Collection

    Object

  • 8/12/2019 31.Java Collections Framework

    31/62

    AbstractSet

    Has code for these methods (shared, andpossibly overridden, by all later

    implementations of Set):

    equalshashCoderemoveAll

    24 April 2013 OSU CSE 31

  • 8/12/2019 31.Java Collections Framework

    32/62

  • 8/12/2019 31.Java Collections Framework

    33/62

    HashSet

    Uses hashingin the Setrepresentation Has code for these methods (overriding

    those in AbstractSet):

    addremoveclearclone

    24 April 2013 OSU CSE 33

    The first three methods,though optional, are

    implemented here and do what

    you should expect.

  • 8/12/2019 31.Java Collections Framework

    34/62

    HashSet

    Uses hashingin the Setrepresentation Has code for these methods (overriding

    those in AbstractSet):

    addremoveclearclone

    24 April 2013 OSU CSE 34

    The clonemethod makes ashallow copy, i.e., the

    elements are not cloned;

    which raises many questions.Best practice: do not use it!

  • 8/12/2019 31.Java Collections Framework

    35/62

    TreeSet

    Uses a balanced binary search tree asthe Setrepresentation

    Has code for several methods (overridingthose in AbstractSet)

    24 April 2013 OSU CSE 35

  • 8/12/2019 31.Java Collections Framework

    36/62

    Overview of ListClasses

    24 April 2013 OSU CSE 36

    List

    ArrayList

    AbstractList

    LinkedList

    Collection

    Iterable

    Abstract-Collection

    Object

  • 8/12/2019 31.Java Collections Framework

    37/62

    AbstractList

    Has code for many methods (shared, andpossibly overridden, by all later

    implementations of List)

    Similar to AbstractSetbut with code formany more methods (because Listhas

    many more potentially layered methods

    than Set)

    24 April 2013 OSU CSE 37

  • 8/12/2019 31.Java Collections Framework

    38/62

    ArrayList

    Uses arraysin the Listrepresentation Has code for many methods (overriding

    those in AbstractList)

    24 April 2013 OSU CSE 38

  • 8/12/2019 31.Java Collections Framework

    39/62

    LinkedList

    Uses a doubly-linked listas the Listrepresentation

    Has code for many methods (overridingthose in AbstractList)

    There is even more detail to the interfacesand abstract classes related to

    LinkedList, which you can look up ifinterested

    24 April 2013 OSU CSE 39

  • 8/12/2019 31.Java Collections Framework

    40/62

    Overview of MapClasses

    24 April 2013 OSU CSE 40

    HashMap TreeMap

    Map

    AbstractMap

    Object

  • 8/12/2019 31.Java Collections Framework

    41/62

    AbstractMap

    Has code for many methods (shared, andpossibly overridden, by all later

    implementations of Map)

    Similar to AbstractSetbut with code formany more methods (because Maphas

    many more potentially layered methods

    than Set)

    24 April 2013 OSU CSE 41

  • 8/12/2019 31.Java Collections Framework

    42/62

    HashMap

    Uses hashingin the Maprepresentation Has code for many methods (overriding

    those in AbstractMap)

    24 April 2013 OSU CSE 42

  • 8/12/2019 31.Java Collections Framework

    43/62

    TreeMap

    Uses a balanced binary search tree asthe Maprepresentation

    Has code for several methods (overridingthose in AbstractMap)

    24 April 2013 OSU CSE 43

  • 8/12/2019 31.Java Collections Framework

    44/62

    JCF Algorithms: Collections

    A number of useful algorithms (and simplebut convenient utilities) to process

    collections are static methods in the

    class Collections, e.g.:sortreversemin, maxshufflefrequency

    24 April 2013 OSU CSE 44

  • 8/12/2019 31.Java Collections Framework

    45/62

    JCF Algorithms: Collections

    A number of useful algorithms (and simplebut convenient utilities) to process

    collections are static methods in the

    class Collections, e.g.:sortreversemin, maxshufflefrequency

    24 April 2013 OSU CSE 45

    Notice that the classCollectionsis different

    from the interface

    Collection, and in

    particular it does not

    implement that interface!

  • 8/12/2019 31.Java Collections Framework

    46/62

    JCF Utilities: Arrays

    A number of useful algorithms (and simplebut convenient utilities) to process built-in

    arrays are static methods in the class

    Arrays, e.g.:sortfilldeepEqualsdeepHashCodedeepToString

    24 April 2013 OSU CSE 46

  • 8/12/2019 31.Java Collections Framework

    47/62

    OSU CSE vs.JCF Components

    The OSU CSE components are similar indesign to the JCF interfaces and classes

    Though some differences can beattributed to pedagogical concerns, there

    are other important technical differences,

    too!

    24 April 2013 OSU CSE 47

  • 8/12/2019 31.Java Collections Framework

    48/62

    Difference #1: Level of Formalism

    JCF interfaces include only informalJavadoc comments forcontracts (rather

    than using explicit mathematical models

    and requires/ensures clauses) JCF descriptions and contracts use similar

    terms, though; e.g.,collections may:

    be ordered or unordered

    have duplicates or not have duplicates

    24 April 2013 OSU CSE 48

  • 8/12/2019 31.Java Collections Framework

    49/62

    Difference #1: Level of Formalism

    JCF interfaces include only informalJavadoc comments forcontracts (rather

    than using explicit mathematical models

    and requires/ensures clauses) JCF descriptions and contracts use similar

    terms, though; e.g.,collections may:

    be ordered or unordered

    have duplicates or not have duplicates

    24 April 2013 OSU CSE 49

    JCF java.util.Set:

    booleanadd(E e)Adds the specified element to this set if it is not already present (optional operation). More formally, adds thespecified element eto this set if the set contains no element e2such that

    (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the setunchanged and returns false. In combination with the restriction on constructors, this ensures that sets never

    contain duplicate elements.

    The stipulation above does not imply that sets must accept all elements; sets may refuse to add any particular

    element, including null, and throw an exception, as described in the specification for Collection.add.Individual set implementations should clearly document any restrictions on the elements that they may contain.

    Throws:

    UnsupportedOperationException- if the add operation is not supported by this setClassCastException- if the class of the specified element prevents it from being added to this setNullPointerException- if the specified element is null and this set does not permit null elementsIllegalArgumentException- if some property of the specified element prevents it from being added to this

    set

  • 8/12/2019 31.Java Collections Framework

    50/62

  • 8/12/2019 31.Java Collections Framework

    51/62

    Difference #1: Level of Formalism

    JCF interfaces include only informalJavadoc comments forcontracts (rather

    than using explicit mathematical models

    and requires/ensures clauses) JCF descriptions and contracts use similar

    terms, though; e.g.,collections may:

    be ordered or unordered

    have duplicates or not have duplicates

    24 April 2013 OSU CSE 51

    HypotheticalOSU CSE components.set.Set:

    booleanadd(T x)

    Can you write a formal contract for the addmethod as it

    is designed in java.util.Set?

  • 8/12/2019 31.Java Collections Framework

    52/62

    Difference #1: Level of Formalism

    JCF interfaces include only informalJavadoc comments forcontracts (rather

    than using explicit mathematical models

    and requires/ensures clauses) JCF descriptions and contracts use similar

    terms, though; e.g.,collections may:

    be ordered or unordered

    have duplicates or not have duplicates

    24 April 2013 OSU CSE 52

    Warning about the JCF documentation:The interface/class summary at the top of the

    Javadoc-generated page sometimes contains

    information that is missing from, or even apparentlycontradictory to, the method descriptions; e.g.:

    iteratorfor SortedSet a few methods for PriorityQueue

  • 8/12/2019 31.Java Collections Framework

    53/62

    Difference #2: Parameter Modes

    JCF interfaces do not have any notion ofparameter modes (rather than using them

    in contracts to help clarify and simplify

    behavioral descriptions) If the JCF used parameter modes, though, the

    default mode also would be restores, as with

    the OSU CSE components

    24 April 2013 OSU CSE 53

  • 8/12/2019 31.Java Collections Framework

    54/62

    Difference #3: Aliasing

    JCF interfaces almost never explicitlymention aliasing (rather than advertising

    aliasing when it may arise)

    JCF components also are notdesigned to tryto avoid aliasing whenever possible, as the

    OSU CSE components are

    24 April 2013 OSU CSE 54

  • 8/12/2019 31.Java Collections Framework

    55/62

    Difference #4: Null

    JCF interfaces generally permit nullreferences to be stored in collections

    (rather than having a blanket prohibition

    against null references) JCF components do, however, sometimes

    include warnings against null references,

    which the OSU components always prohibit

    24 April 2013 OSU CSE 55

  • 8/12/2019 31.Java Collections Framework

    56/62

    Difference #5: Optional Methods

    JCF interfaces generally have optionalmethods (rather than requiring all methods

    to behave according to their specifications

    in all implementations) JCF implementations of the same interface

    are therefore notplug-compatible: optional

    methods have bodies, but calling one mightsimply throw an exception:

    UnsupportedOperationException

    24 April 2013 OSU CSE 56

  • 8/12/2019 31.Java Collections Framework

    57/62

    Difference #6: Copy Constructors

    By convention, every class in the JCF hastwo standard constructors:

    A default constructorA conversion constructorthat copies

    references to the elements of its argument,

    which is another JCF collection

    24 April 2013 OSU CSE 57

  • 8/12/2019 31.Java Collections Framework

    58/62

    Difference #6: Copy Constructors

    By convention, every class in the JCF hastwo standard constructors:

    A default constructorA conversion constructorthat copies

    references to the elements of its argument,

    which is another JCF collection

    24 April 2013 OSU CSE 58

    This no-argument constructor

    creates an empty collection.

  • 8/12/2019 31.Java Collections Framework

    59/62

    Difference #6: Copy Constructors

    By convention, every class in the JCF hastwo standard constructors:

    A default constructorA conversion constructorthat copies

    references to the elements of its argument,

    which is another JCF collection

    24 April 2013 OSU CSE 59

    Presumably, copying from a

    collection that may haveduplicates, to one that may not,

    simply removes extra copies.

  • 8/12/2019 31.Java Collections Framework

    60/62

  • 8/12/2019 31.Java Collections Framework

    61/62

    Difference #8: Kernel Methods

    A single JCF interface usually contains allmethods applicable to a type (rather than

    kernel methods being separated into a

    separate interface from all other methods) JCF uses abstract classes, however, to

    provide default implementations of methods

    that presumably would be implemented inabstract classes in the OSU CSE components

    Other JCF methods are like kernel methods24 April 2013 OSU CSE 61

  • 8/12/2019 31.Java Collections Framework

    62/62