11.Collection

Embed Size (px)

Citation preview

  • 8/12/2019 11.Collection

    1/29

    Java Collection API

  • 8/12/2019 11.Collection

    2/29

    Overview of Collection

    A collection is a group of data manipulate as a single

    object.Corresponds to a bag. Insulate client programs from the implementation. array, li

    list, hash table, balanced binary tree.

    Like C++'s Standard Template Library (STL)

    Can grow as necessary. Contain only Objects (reference types).

    Heterogeneous.

    Can be made thread safe (concurrent access).

    Can be made not-modifiable

  • 8/12/2019 11.Collection

    3/29

    Collection Interfaces

  • 8/12/2019 11.Collection

    4/29

  • 8/12/2019 11.Collection

    5/29

    The Collection Interface

    / / For Basic Operations

    int size();

    boolean isEmpty();

    boolean contains(Object element);

    boolean add(Object element); boolean remove(Object element); //

    Iterator iterator();

  • 8/12/2019 11.Collection

    6/29

  • 8/12/2019 11.Collection

    7/29

    The List Interface

    The List interface corresponds to an order group of elements

    Duplicates are allowed. Extensions compared to the Collection interface

    Access to elements via indexes, like arrays

    add (int, Object), get(int), remove(int),

    set(int, Object) (note set = replace bad name for the method)

    Search for elements indexOf(Object), lastIndexOf(Object)

    Specialized Iterator, call ListIterator

    Extraction of sublist

    subList(int fromIndex, int toIndex)

  • 8/12/2019 11.Collection

    8/29

    The List Interface, cont.

    Further requirements compared to the Collection

    Interface add(Object)adds at the end of the list.

    remove(Object)removes at the start of the list.

    list1.equals(list2) the ordering of the elements is tainto consideration.

    list1.equals(list2) implies that

    list1.hashCode()==list2.hashCode()

  • 8/12/2019 11.Collection

    9/29

    The List Interface, cont. public interface List extends Collection {

    // Positional Access

    Object get(int index); Object set(int index, Object element); // Optional

    void add(int index, Object element); // Optional

    Object remove(int index); // Optional

    abstract boolean addAll(int index, Collection c);

    // Search

    int indexOf(Object o); int lastIndexOf(Object o);

    // Iteration ListIterator listIterator();

    ListIterator listIterator(int index);

    }

  • 8/12/2019 11.Collection

    10/29

    ArrayList Class The classes ArrayListand LinkedList implement the List

    interface.

    ArrayList is an array based implementation where elementaccessed directly via the getand setmethods.

    Default choice for simple sequence.

    It uses a dynamic array for storing the elements.

    It can contain duplicate elements.

    It maintains insertion order. It is not synchronized.

    It allows random access because array works at the index b

    Its manipulation is slower because a lot of shifting needs toccurred.

  • 8/12/2019 11.Collection

    11/29

    E l A Li t t i d fi d bj t

  • 8/12/2019 11.Collection

    12/29

    Example: ArrayList storing user defined objectsimportjava.util.*;

    classSimple{

    publicstaticvoidmain(String args[]){

    Student s1=new Student(101,"Sonoo",23);

    Student s2=new Student(102,"Ravi",21);Student s2=new Student(103,"Hanumat",25);

    ArrayList al=newArrayList();

    al.add(s1);

    al.add(s2);

    al.add(s3);

    Iterator itr=al.iterator();

    while(itr.hasNext()){

    Student st=(Student)itr.next();

    System.out.println(st.rollno+" "+st.name+" "+st.age);

    }

    }

    }

  • 8/12/2019 11.Collection

    13/29

    LinkedList Classes

    LinkedList is based on a double linked list

    Gives better performance on add andremove comparedArrayList.

    Gives poorer performance on get andset methods comptoArrayList.

    It can contain duplicate elements.

    It maintains insertion order.

    It is not synchronized. No random access.

    It can be manipulated faster because no shifting needs to boccurred.

    It can be used as list, stack or queue.

    k d l

  • 8/12/2019 11.Collection

    14/29

    LinkedList Exampleimportjava.util.*;

    classSimple{

    publicstaticvoidmain(String args[]){

    LinkedList al=newLinkedList();

    al.add("Ravi");

    al.add("Vijay");

    al.add("Ravi");

    al.add("Ajay");

    Iterator itr=al.iterator();

    while(itr.hasNext()){

    System.out.println(itr.next());

    }

    }

  • 8/12/2019 11.Collection

    15/29

    The Set Interface

    Corresponds to the mathematical definition of a set (no

    duplicates are allowed).

    Compared to the Collection interface

    Interface is identical.

    Every constructor must create a collection without

    duplicates.

    The operation add cannot add an element already

    the set.

    The method call set1.equals(set2) works at follows

    set1 union set2, and set2 union set1.

  • 8/12/2019 11.Collection

    16/29

    E H hS

  • 8/12/2019 11.Collection

    17/29

    Ex: HashSetimportjava.util.*;

    classSimple{

    publicstaticvoidmain(String args[]){

    HashSet al=newHashSet();al.add("Ravi");

    al.add("Vijay");

    al.add("Ravi");

    al.add("Ajay");

    Iterator itr=al.iterator();

    while(itr.hasNext()){

    System.out.println(itr.next());

    }

    }

  • 8/12/2019 11.Collection

    18/29

  • 8/12/2019 11.Collection

    19/29

    TreeSet

    Implemented using a tree structure.

    Guaranteesordering of elements.(maintainsascending order)

    add, remove, and contains methods

    logarithmic time complexityO(log (n)), whern is the number of elements in the set.

    E T S

  • 8/12/2019 11.Collection

    20/29

    Ex: TreeSetimportjava.util.*;

    classSimple{

    publicstaticvoidmain(String args[]){

    TreeSet al=newTreeSet();

    al.add("Ravi");

    al.add("Vijay");

    al.add("Ravi");

    al.add("Ajay");

    Iterator itr=al.iterator();

    while(itr.hasNext()){

    System.out.println(itr.next());

  • 8/12/2019 11.Collection

    21/29

    Map Interface

    A Map is an object that maps keys to values. Also called an

    associative array or a dictionary.

    Methods for adding and deleting

    put(Object key, Object value)

    remove (Object key)

    Methods for extraction objects

    get (Object key)

    Methods to retrieve the keys, the values, and (key, value) pairs

    keySet() // returns a Set

    values() // returns a Collection,

    entrySet() // returns a set

    MAP Interface methods

  • 8/12/2019 11.Collection

    22/29

    MAP Interface methods public interface Map {

    // Basic Operations

    Object put(Object key, Object value);

    Object get(Object key);

    Object remove(Object key);

    boolean containsKey(Object key);

    boolean containsValue(Object value);

    int size();

    boolean isEmpty();

    // Bulk Operations void putAll(Map t);

    void clear();

    // Collection Views

    public Set keySet();

    public Collection values();

    public Set entrySet();

  • 8/12/2019 11.Collection

    23/29

    HashMap and TreeMap Classes

    The HashMap and TreeMap classes implement the Ma

    interface.

    HashMap

    The implementation is based on a hash table.

    No ordering on (key, value) pairs.

    A HashMap contains values based on the key. It contains only unique elements.

    It may have one null key and multiple null values.

    EX H hM

  • 8/12/2019 11.Collection

    24/29

    EX: HashMapimportjava.util.*;

    classSimple{

    publicstaticvoidmain(String args[]){

    HashMap hm=newHashMap();

    hm.put(100,"Amit");

    hm.put(101,"Vijay");

    hm.put(102,"Rahul");

    Set set=hm.entrySet();Iterator itr=set.iterator();

    while(itr.hasNext()){

    Map.Entry m=(Map.Entry)itr.next();

    System.out.println(m.getKey()+" "+m.getValue());

    }

  • 8/12/2019 11.Collection

    25/29

    TreeMap

    The implementation is based on tree structure.

    (key, value) pairs are ordered on the key.(ascending)

    A TreeMap contains values based on the key.

    It contains only unique elements.

    It cannot have null key but can have multiple null valu

    It is same as HashMap instead maintains ascending o

    Ex: TreeMap

  • 8/12/2019 11.Collection

    26/29

    Ex: TreeMapimportjava.util.*;

    classSimple{

    publicstaticvoidmain(String args[]){

    TreeMap hm=newTreeMap();

    hm.put(100,"Amit");

    hm.put(102,"Ravi");

    hm.put(101,"Vijay");

    hm.put(103,"Rahul");

    Set set=hm.entrySet();

    Iterator itr=set.iterator();

    while(itr.hasNext()){

    Map.Entry m=(Map.Entry)itr.next();

    System.out.println(m.getKey()+" "+m.getValue());

    }

    Utility methods of Collections

  • 8/12/2019 11.Collection

    27/29

    Utility methods of Collections

    All the methods of class Collections are static

    Search and sort:binarySearch(), sort() Reorganization: reverse(), shuffle()

    Wrappings: unModifiableCollection,

    synchonizedCollection

    C ll i Ad & di d

  • 8/12/2019 11.Collection

    28/29

    Collection Advantages & disadvantages

    Advantages:

    Can hold different types of objects. Resizable

    Disadvantages

    Must cast to correct type

    Cannot do compile-time type checking.

  • 8/12/2019 11.Collection

    29/29

    Thank You