CollectionFramework In core Java

55
Sessi on 3 - Exception-Handling Java Prorammin 1 1 TCS Confidential Collection Framework (java.util Package)

description

Collection framework in java

Transcript of CollectionFramework In core Java

  • Session 3 - Exception-Handling Java Programming

    11TCS Confidential

    Collection Framework(java.util Package)

  • Session 3 - Exception-Handling Java Programming

    22TCS Confidential

    Framework (in software):a general system of components for architectural solutions.

    Collection:any collection of Objects

  • Session 3 - Exception-Handling Java Programming

    33TCS Confidential

    Overview (contd) Collection, Iterator Lists, ListIteratorListArrayListLinkedList

    Stack Queue,

    PriorityQueue

    SetsSetTreeSetHashSet

    MapsMapTreeMapHashMap

    All the interfaces and classes are part of the java.util package.

  • Session 3 - Exception-Handling Java Programming

    44TCS Confidential

    Overview (contd)

    interfaceCollection

    interfaceIterator

    interfaceComparable

    interfaceComparator

    interfaceQueue

    interfaceMap

    Stack PriorityQueue

    HashMapTreeMap

    LinkedListArrayList TreeSet HashSet

    interfaceList

    interfaceSet

    interfaceListIterator

    CollectionSet

    TreeSetHashSet

    ListArrayList

    LinkedList

    TreeSetTreeMap

    PriorityQueue

  • Session 3 - Exception-Handling Java Programming

    55TCS Confidential

    Holds references to objects Can contain references to two

    equal objects.(a.equals (b)) An object can change while in a

    collection (unless it is immutable).

  • Session 3 - Exception-Handling Java Programming

    66TCS Confidential

    Overview (contd)CollectionListStackSet

    A map takes two object type parameters:Map

    Because collections work with different types, these are called generic collections or generics

  • Session 3 - Exception-Handling Java Programming

    77TCS Confidential

    Collection, Iterator Collection interface

    represents any collection. A collection has its own

    iterator(s).(returned iterator method);The traversal sequencedepends on the collection.

    interfaceCollection

    interfaceIterator

  • Session 3 - Exception-Handling Java Programming

    88TCS Confidential

    Collection Methods

    boolean isEmpty ()int size ()boolean contains (Object obj)boolean add (E obj)boolean remove (E obj)Iterator iterator ()

    Supplies an iterator for this collection

    interfaceCollection

    interfaceIterator

  • Session 3 - Exception-Handling Java Programming

    99TCS Confidential

    Iterator Methods

    boolean hasNext ()E next ()void remove ()

    What is next is determined

    Removes the last visited element

    interfaceCollection

    interfaceIterator

  • Session 3 - Exception-Handling Java Programming

    1010TCS Confidential

    Iterator For Each Loop

    Iterator iter =words.iterator();

    while (iter.hasNext ()){String word = iter.next ();

    < ... process word > }

    Collection words = new ArrayList();

  • Session 3 - Exception-Handling Java Programming

    1111TCS Confidential

    Lists, ListIterator In a list all elements are numbered

    a0, a1, ..., an-1 java.util:List interfaceArrayListLinkedList

    ListIterator is an extended iterator, (subinterface of Iterator)

  • Session 3 - Exception-Handling Java Programming

    1212TCS Confidential

    Lists (contd)

    interfaceCollectioninterfaceIterator

    interfaceListIterator

    ArrayList LinkedList

    interfaceSet

    interfaceList

  • Session 3 - Exception-Handling Java Programming

    1313TCS Confidential

    E get (int i)E set (int i, E obj)void add (int i, E obj)E remove (int i)int indexOf (Object obj)ListIterator listIterator ()

    ListIterator listIterator (int i)

    List Methods interfaceCollectioninterfaceIterator

    interfaceListIterator

    interfaceList

    Returns a ListIterator that starts iterations at index i

  • Session 3 - Exception-Handling Java Programming

    1414TCS Confidential

    ListIterator Methodsint nextIndex ()

    boolean hasPrevious ()E previous ()int previousIndex ()void add (E obj)void set (E obj)

    Can traverse the list backward

    (inserts after the last visited element)

    Can change elements (changes the last visited element)

  • Session 3 - Exception-Handling Java Programming

    1515TCS Confidential

    ArrayList Represents a list as adynamic array Provides random access to the

    elements Implements all the methods of

    List

    interfaceList

    ArrayList LinkedList

    ...

  • Session 3 - Exception-Handling Java Programming

    1616TCS Confidential

    LinkedList

    Doubly-linked list with a header node.

    Implements the methods of List

    a0 a1 a2 an-1...

    header

    interfaceList

    ArrayList LinkedList

  • Session 3 - Exception-Handling Java Programming

    1717TCS Confidential

    LinkedList (contd)

    Additional methods

    interfaceList

    ArrayList LinkedList

    void addFirst (E obj)void addLast (E obj)E getFirst ()E getLast ()E removeFirst ()E removeLast ()

  • Session 3 - Exception-Handling Java Programming

    1818TCS Confidential

    ArrayList vs. LinkedList Implements

    array+Provides

    random access- Insert, removing

    elements shifts elements

    - Needs to be resized

    Implements list -No random access

    +Insert, removing elements is done by rearranging the links

    +Nodes are dynamically added

  • Session 3 - Exception-Handling Java Programming

    1919TCS Confidential

    ArrayList vs. LinkedList (contd)

    for (int i = 0; i < list.size(); i++){

    Object x = list.get (i);...

    }

    Iterator iter = list.iterator ( );while (iter.hasNext ( )){

    Object x = iter.next ( );...

    }

    for (Object x : list){

    ...}

  • Session 3 - Exception-Handling Java Programming

    2020TCS Confidential

    Stacks

    Provides temporary storage LIFO (Last-In-First-Out) manner.

    Useful in nested structuresmethods calling other methods

    push and pop. Implemented as java.util.Stack

    class

  • Session 3 - Exception-Handling Java Programming

    2121TCS Confidential

    Stacks (contd)

    Stack

  • Session 3 - Exception-Handling Java Programming

    2222TCS Confidential

    Stack Methods

    boolean isEmpty ()E push (E obj)E pop ()E peek ()

    Returns obj; use as void

    Returns the top element without removing it from the stack

  • Session 3 - Exception-Handling Java Programming

    2323TCS Confidential

    Queues Provides temporary storage in

    the FIFO manner. Useful in events that have to be

    processed in order of their arrival

    java.util:Queue interfaceLinkedList (implements Queue)

  • Session 3 - Exception-Handling Java Programming

    2424TCS Confidential

    Queues (contd)

    LinkedList

    interfaceQueue

  • Session 3 - Exception-Handling Java Programming

    2525TCS Confidential

    QueueMethods

    LinkedList

    interfaceQueue

    boolean isEmpty ()boolean add (E obj)E remove ()E peek () Returns the first element

    without removing it from the queue

  • Session 3 - Exception-Handling Java Programming

    2626TCS Confidential

    Queues (contd)

    Queue q =new LinkedList ();

    Methods added to LinkedList to implement Queue interface:

    add == addLastremove== removeFirstpeek == getFirst

  • Session 3 - Exception-Handling Java Programming

    2727TCS Confidential

    Priority Queues

    In a priority queue, items are processed NOT in order of arrival, but in order of priority.

    java.util:Queue interfacePriorityQueue (implements Queue)

  • Session 3 - Exception-Handling Java Programming

    2828TCS Confidential

    PriorityQueue

    interfaceQueue

    Priority Queues (contd)

    The same methods as in Queue: isEmpty, add, remove, peek.

  • Session 3 - Exception-Handling Java Programming

    2929TCS Confidential

    Sets A set is without duplicate values Designed for finding a value

    quickly java.util:Set interfaceTreeSetHashSet

  • Session 3 - Exception-Handling Java Programming

    3030TCS Confidential

    Sets (contd)interfaceCollection

    TreeSet HashSet

    interfaceSet

  • Session 3 - Exception-Handling Java Programming

    3131TCS Confidential

    TreeSet

    Works with Comparableobjects

    contains, add, and removemethods

    Iterator returns elements in ascending order

    TreeSet HashSet

    interfaceSet

  • Session 3 - Exception-Handling Java Programming

    3232TCS Confidential

    HashSet

    Works with objects for which reasonable hashCode and equals methods are defined

    contains, add, and removemethods

    Iterator returns elements in no particular order

    TreeSet HashSet

    interfaceSet

  • Session 3 - Exception-Handling Java Programming

    3333TCS Confidential

    Maps

    It represents a correspondence between a set of keys , values

    Only one value can correspond to a given key;

    several keys can be mapped onto the same value

    keys values

  • Session 3 - Exception-Handling Java Programming

    3434TCS Confidential

    Maps (contd)

    TreeMap HashMap

    interfaceMap

  • Session 3 - Exception-Handling Java Programming

    3535TCS Confidential

    Map Methods

    TreeMap HashMap

    interfaceMap

    boolean isEmpty ()int size ()V get (K key)V put (K key, V value)V remove (K key)Set keySet ()

  • Session 3 - Exception-Handling Java Programming

    3636TCS Confidential

    TreeMap

    Works with Comparable keys containsKey, get, and put

    methods

    TreeMap HashSet

    interfaceMap

  • Session 3 - Exception-Handling Java Programming

    3737TCS Confidential

    HashMap

    Works with keys for which reasonable hashCode and equalsmethods are defined

    containsKey, get, and put methods

    TreeMap HashMap

    interfaceMap

  • Session 3 - Exception-Handling Java Programming

    3838TCS Confidential

    Example: traversing all key-value pairsimport java.util.*;

    Map AuctionItems =new TreeMap ();

    AuctionItems.put (1, ARTPEICE);...for (Integer key : AuctionItems.keySet() ){ String name = AuctionItems.get (key);

    System.out.println (key + " : " + name);}

  • Session 3 - Exception-Handling Java Programming

    3939TCS Confidential

    Review: Why Java collections are called generic? Name several methods of Collection. What is an iterator? How can we obtain an iterator for a given

    collection? Guess what happens when we call iter.next()

    when there is no next element.

  • Session 3 - Exception-Handling Java Programming

    4040TCS Confidential

    Review (contd): What are the properties of a list? Name the key methods of the List interface. How is ArrayList implemented? How is LinkedList implemented?

  • Session 3 - Exception-Handling Java Programming

    4141TCS Confidential

    Case Study: Stock Exchange

    Implements a Suryodaya stock exchange

    Uses TreeSet, TreeMap, HashMap, Queue, and PriorityQueue classes

    A chance to practice structural and object-oriented design

  • Session 3 - Exception-Handling Java Programming

    4242TCS Confidential

    Stock Market Basics Stocks are listed on a stock exchange, such

    as Suryodaya Stock Exchange. A particular stock is identified by its trading

    symbol (for example, SUNW for Sun Microsystems or MSFT for Microsoft)

    Stocks are usually traded in multiples of 100 Stock prices are in Rs. Online brokerage firms allow customers to

    trade stocks online from their computers

  • Session 3 - Exception-Handling Java Programming

    4343TCS Confidential

    Stock Market Terms Buy order an order to buy shares of stock Sell order an order to sell shares of stock Limit order specifies the maximum price for

    a buy or a minimum price for a sell Ask asking price for a sell order Bid offer to buy at a certain price Market order an order to buy or sell at the

    market price (the lowest ask or the highest bid, respectively)

  • Session 3 - Exception-Handling Java Programming

    4444TCS Confidential

    SafeTrade Program Registered users trade shares. A user must login first. The program can register a new user. A logged in user can place buy and sell orders

    and get price quotes for stocks. Users receive messages when their orders are

    executed

  • Session 3 - Exception-Handling Java Programming

    4545TCS Confidential

    SafeTrade Program (contd) Runs on a single computer; each active user

    opens a separate trading window. Does not keep track of cash or of the number

    of shares available on each users account.

  • Session 3 - Exception-Handling Java Programming

    4646TCS Confidential

    SafeTrade Program (contd)

  • Session 3 - Exception-Handling Java Programming

    4747TCS Confidential

  • Session 3 - Exception-Handling Java Programming

    4848TCS Confidential

  • Session 3 - Exception-Handling Java Programming

    4949TCS Confidential

    SafeTrade Program Design

    Structural Design

    OODesign

    Detailed Design

    Classes and objects

    Data structures used

    Fields, constructors, and methods

  • Session 3 - Exception-Handling Java Programming

    5050TCS Confidential

    SafeTrade Structural Design

    Queue => PriorityQueue

    (with descending price comparator)

    Buy orders for each stock

    Queue => PriorityQueue

    (with ascending price comparator)

    Sell orders for each stock

    Map => HashMapListed stocks

    Queue => LinkedListMailbox for each trader

    Set => TreeSetLogged-in tradersMap => TreeMapRegistered traders

    interface => classData

  • Session 3 - Exception-Handling Java Programming

    5151TCS Confidential

    Structural Design Tradeoffs

    Registered users: large number (100,000s) access time is not critical

    Binary Search

    Tree (TreeMap)

    Listed stocks: relatively small number fast access time is critical

  • Session 3 - Exception-Handling Java Programming

    5252TCS Confidential

    SafeTrade OO Design

    SafeTrade

    StockExchange Brokerage

    TraderWindow

    Trader Stock

    PriceComparator TradeOrder

    LoginWindow

    interface Login

    StockExchange Brokerage Stock Trader TraderWindow PriceComparator

  • Session 3 - Exception-Handling Java Programming

    5353TCS Confidential

    Part 1: Trader registration and login

    SafeTrade LoginWindow

    interfaceLogin

  • Session 3 - Exception-Handling Java Programming

    5454TCS Confidential

    Part 2: Stocks and ordersTraderWindow