11 1 Collections and Generics

download 11 1 Collections and Generics

of 67

Transcript of 11 1 Collections and Generics

  • 8/14/2019 11 1 Collections and Generics

    1/67

  • 8/14/2019 11 1 Collections and Generics

    2/67

    2Java

    Autoboxing with collections10

    ArrayList9

    List interface methods8

    Classes implementing List interface7

    Iterations6

    Methods of Collection interfaces5Ordered and Sorted collection4

    Collection Classes3

    Collection interfaces2

    Collection framework1

    Contents

  • 8/14/2019 11 1 Collections and Generics

    3/67

    3Java

    Comparator interface20

    Methods19Constructors18

    PriorityQueue17

    LinkedList continues16

    Queue interface methods15

    Classes implementing Queue interface14

    Linked List13

    Stack12

    Vector11

    Contents

  • 8/14/2019 11 1 Collections and Generics

    4/67

    4Java

    Classes implementing Map interface30

    Map interface methods29Methods28

    SortedSet and TreeSet27

    LinkedHashSet26

    Contract25

    hashCode()24

    Constructors and methods23

    HashSet22

    Set interface methods21

    Contents

  • 8/14/2019 11 1 Collections and Generics

    5/67

    5Java

    Converting Collection into arrays38

    Converting arrays into Collection37

    Arrays36

    Collections35

    equals()34

    Methods converting Map into Collection33

    LinkedHashMap and TreeMap32

    HashMap and Hashtable31

    Contents

  • 8/14/2019 11 1 Collections and Generics

    6/67

    6Java

    Know

    The Collection framework

    Collection interfaces and classes

  • 8/14/2019 11 1 Collections and Generics

    7/67

    7Java

    Be Able To

    Use Collections in Java programs

  • 8/14/2019 11 1 Collections and Generics

    8/67

    8Java

    Collection framework

    A collection in java is an object that can hold

    multiple objects (like an array) and that will grow

    dynamically.

    A collection framework is a common architecturefor representing and manipulating all the

    collections.

  • 8/14/2019 11 1 Collections and Generics

    9/67

    9Java

    Collection interfaces

    Collection

    List Set

    Map

    Queue

    List is a collection of objects.Set is a collection of objects that does not allow duplicate

    objects.

    Queue is a collection of objects that arranges objects in FIFO

    order by comparing the objects and has queue like methods.Map contains pairs of objects (each pair comprising of one

    object representing a key and other representing a value ).

    java.util package

    SortedSetSortedMap

  • 8/14/2019 11 1 Collections and Generics

    10/67

    10Java

    Collection Classes

    HashSet

    LinkedHashSet

    TreeSet

    1. Set

    SortedSet

    ArrayList

    Vector

    StackLinkedList

    1. List

    Implementation ClassesInterface

  • 8/14/2019 11 1 Collections and Generics

    11/67

    11Java

    LinkedList

    PriorityQueue

    1. Queue

    HashtableHashMap

    LinkedHashMap

    TreeMap

    1.Map

    SortedMap

    Implementation ClassesInterface

    LinkedList implements List also

    All the above classes are serializable.

  • 8/14/2019 11 1 Collections and Generics

    12/67

    12Java

    Ordered and Sorted

    collection All collection classes that implement List andQueue interface, LinkedHashSet andLinkedHashMap are ordered. The order is based

    on the sequence in which the user enters theobject.

    Hashtable, HashMap, HashSet areunordered collections.

    All the classes that implements SortedMap orSortedSet are sorted. PriorityQueue is alsosorted.

  • 8/14/2019 11 1 Collections and Generics

    13/67

    13Java

    Methods of Collection interfaces

    boolean add(E o)void clear()

    boolean remove(Object o)

    boolean removeAll( Collection c)

    boolean retainAll( Collection c)

    int size()

    boolean isEmpty()

    boolean contains(Object o)

    T[] toArray()

    Iterator iterator()

    For now replace with Object

    Just Collection

    Iterator

  • 8/14/2019 11 1 Collections and Generics

    14/67

    14Java

    Iterations

    void method(Collection coll){

    for(Object c:coll){

    System.out.println(c.toString());}}

    void method(Collection coll){

    for(Iterator i = coll.iterator();i.hasNext(); ){

    Object o= i.next();

    System.out.println(o.toString()); }

    1.4 way using Iterator interface

    1.5 way using for-each loop

  • 8/14/2019 11 1 Collections and Generics

    15/67

    15Java

    Classes implementing List

    interface

  • 8/14/2019 11 1 Collections and Generics

    16/67

    16Java

    List interface methods

    All the methods of Collection interface and thefollowing methods:

    void add(int index, E element)

    E remove(int index)int indexOf(Object o)

    int lastIndexOf(Object o)

    E get(int index)

    E set(int index, E element)

    List subList(int fromIndex,inttoIndex)

    Replace all E by Object

    List

  • 8/14/2019 11 1 Collections and Generics

    17/67

    17Java

    ArrayListThis class implements all the methods of List interface.

    Constructors:

    ArrayList()

    ArrayList(int initialCapacity)

    Capacity 10

    Collection class implementations use dynamicarray- Then why are we talking about capacity ?

    This collection class (and some others)

    internally use array. Capacity is the size

    of the array. As elements are added, if the

    capacity is not sufficient the array is

    reallocated.

  • 8/14/2019 11 1 Collections and Generics

    18/67

    18Java

    Exampleimport java.util.*;

    class Test{

    public static void main(String[] s){

    ArrayList a= new ArrayList();for(String x:s)

    a.add(x);

    for(Object o:a)

    System.out.println(o);

    } }

    adding

    iterating

    Folder 1

  • 8/14/2019 11 1 Collections and Generics

    19/67

    19Java

    Autoboxing with collections

    import java.util.*;class Test{

    public static void main(String[] s){

    ArrayList a= new ArrayList();

    a.add(1);

    a.add("Mary");

    a.add(1.78);

    for(Object o:a)System.out.println(o);

    } }

    Boxed into Integer

    wrapper class

    Boxed into Double

    wrapper class

    Folder 2

  • 8/14/2019 11 1 Collections and Generics

    20/67

    20Java

    I get a warning when Icompile the previousprograms:Note: Test.java uses

    unchecked or unsafeoperations

    Note: Recompile with

    -Xlint:unchecked for

    details.

    A single collection object can holdmany objects of different types(likethe example in the previous slide).

    In 1.5, we can create type-safecollections where we can restrict acollection to hold only particulartype of object.(The syntax toachieve this will be covered in

    generics.) The 1.5 compiler gives awarning message if type safecollection is not used.

  • 8/14/2019 11 1 Collections and Generics

    21/67

    21Java

    Vector

    The Vector class is exactly same as ArrayList classexcept that the Vector class methods are thread-safe.

    Constructor

    Vector()

    Vector(int initialCapacity)Vector(int initialCapacity,int capacityIncrement)

    And all the methods of List interface are implemented.

  • 8/14/2019 11 1 Collections and Generics

    22/67

    22Java

    I was just looking at the API

    documentation, none of themethods of Vector class aremarked as synchronized !

    You wont find it in the API documentation. Butif you are curious you could look at the sourcecode. In your Java home folder look for azipped file called src. Extract the Vector classand look at the source code. The collections

    that have synchronized implementation areVector and its subclasses and Hashtable and

    its subclasses.

  • 8/14/2019 11 1 Collections and Generics

    23/67

    23Java

    Stack Class that represents a stack where objects are

    inserted in LIFO manner. Inherits from the Vector class.

    Constructor

    Stack()

    Methods (apart from Vector methods) E pop()

    E push(E item)

    E peek()boolean empty()

    int search(Object o)

    Replace all E by Object

  • 8/14/2019 11 1 Collections and Generics

    24/67

    24Java

    Linked List

    LinkedList implements List and Queue.

    All the List classes we have seen so far use

    arrays. LinkedList class behaves like doubly-linked list.

    The methods in the LinkedList allow it to be

    used as a stack, queue, or double-ended

    queue.

  • 8/14/2019 11 1 Collections and Generics

    25/67

    25Java

    Classes implementing

    Queue interface

  • 8/14/2019 11 1 Collections and Generics

    26/67

    26Java

    Queue interface methods

    E element()

    E peek()

    boolean offer(E o)

    E poll()

    E remove()

    Methods indicate feature similar to queue.

    Replace all E by Object

    NoSuchElementExceptionif queue is empty

  • 8/14/2019 11 1 Collections and Generics

    27/67

    27Java

    LinkedList continues

    Constructor: LinkedList()

    Methods:Apart from methods of List and Queuesome more convenient methods are added.

    E getFirst()

    E getLast()

    E removeFirst()

    E removeLast()

    void addFirst(E o)

    void addLast(E o)

    Replace all E by Object for now

  • 8/14/2019 11 1 Collections and Generics

    28/67

    28Java

    PriorityQueue

    It is a sorted collection new in 1.5 thatimplements Queue

    Sorting is based on

    the compareTo() method of

    Comparable interface(also called naturalorder).

    the Comparator object passed viaconstructor.

    A PriorityQueue does not permit nullelements.

  • 8/14/2019 11 1 Collections and Generics

    29/67

    29Java

    Constructors

    PriorityQueue()

    PriorityQueue(int initialCapacity)

    PriorityQueue(int initialCapacity,

    Comparator

  • 8/14/2019 11 1 Collections and Generics

    30/67

    30Java

    Yes!

    I see capacity in the constructor.

    Does that mean that thePriorityQueue uses arrays?

  • 8/14/2019 11 1 Collections and Generics

    31/67

    31Java

    Methods

    All the methods of Queue interface (dont forget

    the Queue interface extends Collection interface)

    and

    Comparator

  • 8/14/2019 11 1 Collections and Generics

    32/67

    32Java

    import java.util.*;

    public class NaturalOrder {public static void main(String str[])

    throws general.InvalidNameException {

    student.Student s1= new

    student.Student("Rama");

    student.Student s2= new

    student.Student("Sita");

    student.Student s3= newstudent.Student("Hunuman");

    student.Student s4= new

    student.Student("Ravana");

    Example with natural ordering

    Folder 3

  • 8/14/2019 11 1 Collections and Generics

    33/67

    33Java

    PriorityQueue p= new PriorityQueue();

    p.offer(s1);

    p.offer(s2);p.offer(s3);

    p.offer(s4);

    while(!p.isEmpty()) {

    student.Students=(student.Student)p.poll();

    System.out.println(s.getName()+ " "

    +s.getRegNo() );

    } } }Result: Hunuman 3

    Rama 1

    Ravana 4

    Sita 2

    Method declared in Collection

    interface. Queue interfaceextends Collection interface

    Casting Object instance into

    Student instance

  • 8/14/2019 11 1 Collections and Generics

    34/67

    34Java

    Comparator interface

    A class that implements Comparator interface must

    override

    int compare(T o1, T o2)

    (Replace T by Object)

    The next example uses Comparator to change the

    ordering of the Student elements in the

    PriorityQueue class.

  • 8/14/2019 11 1 Collections and Generics

    35/67

    35Java

    import java.util.*;

    class StudentComparator implements

    Comparator{

    public int compare(Object o1, Object

    o2){

    student.Student s1=(student.Student)o1;

    student.Student s2=(student.Student)

    o2;

    return s1.getCurrentSemester() -s2.getCurrentSemester();

    }

    }Folder 4

  • 8/14/2019 11 1 Collections and Generics

    36/67

    import java.util.*;

    public class ComparatorOrder {

    public static void main(String str[]) throws

    general.InvalidNameException {

    student.Student s1= new

    student.Student("Rama");

    s1.setCurrentSemester(1);

    student.Student s2= newstudent.Student("Sita");

    s2.setCurrentSemester(4);

    student.Student s3= new

    student.Student("Hunuman");s3.setCurrentSemester(2);

    student.Student s4= new

    student.Student("Ravana");

    s4.setCurrentSemester(3);

  • 8/14/2019 11 1 Collections and Generics

    37/67

    PriorityQueue p= new PriorityQueue(4,new

    student.StudentComparator());

    p.offer(s1); p.offer(s2); p.offer(s3); p.offer(s4);

    while(!p.isEmpty()) {

    student.Student s=(student.Student)p.poll();

    System.out.println(s.getName()+ " in semester" +s.getCurrentSemester() );

    } }}

    Result:

    Rama in semester 1

    Hunuman in semester 2

    Ravana in semester 3

    Sita in semester 4

  • 8/14/2019 11 1 Collections and Generics

    38/67

    38Java

    Set interface methods

    As stated earlier a set cannot contain duplicate

    elements.

    It can contain at most one null element.

    Set does not add any new methods apart from

    what it gets from Collection interface.

    Classes implementing Set must return false if

    an attempt is made to add duplicate element.

  • 8/14/2019 11 1 Collections and Generics

    39/67

    39Java

    HashSet

    HashSet is an unordered and unsorted collection.

    This class uses hashCode() method of the object

    added in the collection to determine how the

    element should be ordered in the collection. Positioning elements using hashCode() helps in

    faster retrieval. So, more efficient the hashCode(),

    better the performance.

    Object class implements hashCode() method that

    returns distinct integers for distinct objects.

  • 8/14/2019 11 1 Collections and Generics

    40/67

    40Java

    When I say they areunordered andunsorted, I mean itfrom end user pointof view.

    Wait a minute-you say thatthe HashSet collection isordered

    according tohashCode() method on onehand and on the other handyou say that it is unorderedand unsorted collection. ??!!

  • 8/14/2019 11 1 Collections and Generics

    41/67

    41Java

    Constructors and methods

    HashSet()

    HashSet(int initialCapacity)

    and all the Set methods

    h hC d ()

  • 8/14/2019 11 1 Collections and Generics

    42/67

    42Java

    hashCode() For efficient performance with HashSet collection,

    the hashCode() method for the object(that is goingto be added to the collection) must be overridden.

    LJIF

    0 1 2 24 25

    new Student("Raja)

    new Student("Rani")

    new Student("Maha)

    new Teacher("Shree"

    called buckets

    Overriding hashCode() in Person class such that persons whose name start

    with A go inside one bucket and persons whose name start with B go inside

    another bucket and so on..

  • 8/14/2019 11 1 Collections and Generics

    43/67

    43Java

    Contract

    Whenever hashCode() is invoked on the sameobject more than once during an execution of a

    Java application, the hashCode method must

    consistently return the same integer, provided

    no information used in equals comparisons onthe object is modified. This integer need not

    remain consistent from one execution of an

    application to another execution of the same

    application.

  • 8/14/2019 11 1 Collections and Generics

    44/67

    44Java

    If two objects are equal according to theequals(Object) method, then calling the hashCode

    method on each of the two objects must producethe same integer result.

    It is not required that if two objects are unequal

    according to the equals(java.lang.Object) method,then calling the hashCode method on each of thetwo objects must produce distinct integer results.However, the programmer should be aware thatproducing distinct integer results for unequalobjects may improve the performance ofhashtables.

  • 8/14/2019 11 1 Collections and Generics

    45/67

    45Java

    package general;public abstract class Person{

    .

    public int hashCode(){

    return name.charAt(0);}

    }

    Folder 5

  • 8/14/2019 11 1 Collections and Generics

    46/67

    46Java

    import java.util.*;

    public class TestHashSet {

    public static void main(String str[])

    throws Exception {teacher.Teacher s1= new

    teacher.Teacher("Guru");

    student.Student s2= new

    student.Student("Shree");

    teacher.Teacher s3= new

    teacher.Teacher("Kumar");

    student.Student s4= newstudent.Student(Sheela");

    HashSet set= new HashSet();

    set.add(s1); set.add(s2);

    set.add(s3); set.add(s4);

  • 8/14/2019 11 1 Collections and Generics

    47/67

    47Java

    Iterator i= set.iterator();

    while(i.hasNext()){

    general.Person p= (general.Person)

    i.next();

    System.out.println(p.getName());

    } } }

    Result:

    Sheela

    ShreeKumar

    Guru

    Into one bucket

  • 8/14/2019 11 1 Collections and Generics

    48/67

    48Java

    LinkedHashSet

    Maintains the insertion-order and does not allowduplicates. Insertion order is not affected if anelement is re-inserted into the set.

    It also uses hashing technique internally for

    searching and retrieving. Constructor and methods:

    LinkedHashSet()

    And all the Set interface methods.

  • 8/14/2019 11 1 Collections and Generics

    49/67

    49Java

    SortedSetand TreeSet

    Classes implementing this interfaceguarantees that while traversing the order willbe either

    B. in natural order (using compareTo() ofComparable interface)

    or

    by using a Comparator provided at creation

    time. There is only one class implementing this

    interface: TreeSet

    M th d

  • 8/14/2019 11 1 Collections and Generics

    50/67

    50Java

    MethodsE first()

    E last()

    Comparator

  • 8/14/2019 11 1 Collections and Generics

    51/67

    51Java

    Map interface methods

    Methods:boolean containsKey(Object key)

    boolean containsValue(Object value)

    V get(Object key)V put(K key, V value)

    V remove(Object key)

    Set keySet()Collection values()

    Replace all V by Object. And ignore

  • 8/14/2019 11 1 Collections and Generics

    52/67

    52Java

    Classes implementing Map

    interface

  • 8/14/2019 11 1 Collections and Generics

    53/67

    53Java

    HashMap and Hashtable

    Both of the classes arrange the pair of objectswith respect to hashCode() of the key and the

    keys map to a value.

    Constructors:

    HashMap()

    HashMap(int initialCapacity)

    Hashtable()

    Hashtable (int initialCapacity)

    The only difference between HashMap and

    Hashtable is that Hashtable is thread-safe.

  • 8/14/2019 11 1 Collections and Generics

    54/67

    54Java

    import java.util.*;

    public class MyDictionary{public static void main(String str[]) {

    HashMap h= new HashMap();

    // adding words and their meanings

    h.put("benevolent",new String[]{"kind",

    "generous","warm-hearted"});

    h.put("chastity",new String[]{"purity","self-restraint","warm-hearted"});

    h.put("dingy", new String[]{"dark",worn"});Folder 6

  • 8/14/2019 11 1 Collections and Generics

    55/67

    55Java

    h.put("gait",new

    String[]{"walk","step","stride"});

    // reading the word from the console

    Scanner scan= new Scanner(System.in);

    String word=scan.next().toLowerCase();

    String meaning[]=(String [])h.get(word);

    for(String

    m:meaning)System.out.println(m);

    }

    }

  • 8/14/2019 11 1 Collections and Generics

    56/67

    56Java

    LinkedHashMap and TreeMap

    LinkedHashMap isparallel to

    LinkedHashSet andTreeMap is parallel to

    TreeSet. Do you see thepattern? Try answering

    the questions in thenext slide to test your

    understanding.

  • 8/14/2019 11 1 Collections and Generics

    57/67

    57Java

    Methods converting Map into

    Collection

    Set keySet() Collection values() Set entrySet()

    Map.Entry is an interface with methods:K getKey()V getValue()

    V setValue(V value)

  • 8/14/2019 11 1 Collections and Generics

    58/67

    58Java

    Questions

    1. Which among LinkedHashMap and TreeMapa) is a ordered collection

    b) is a sorted collection

    c) uses hashingd) has synchronized implementation

    e) uses Comparable or Comparator

    equals()

  • 8/14/2019 11 1 Collections and Generics

    59/67

    59Java

    equals()

    equals() method for all the classes in collection

    framework is overridden.boolean equals(Object o)

    The equals() methods can be used to compare theequality of collection of similar type rater than just its

    own type. For example for Lists, it returns true if and only if the

    specified Object is also a List, both Lists have thesame size, and all corresponding pairs of elements

    in the two Lists are equal. Same is for the classes which implement Map and

    Set.

    C ll ti

  • 8/14/2019 11 1 Collections and Generics

    60/67

    60Java

    Collections This class does some general operations with

    collections like searching, filling, copying, gettingthe maximum and minimum of collection etc. Allthe methods in this class are static.

    Searching Methods:

    static int binarySearch(List

  • 8/14/2019 11 1 Collections and Generics

    61/67

    61Java

    static int binarySearch(List

  • 8/14/2019 11 1 Collections and Generics

    62/67

    62Java

    Filling Method:

    static void fill(List list, Object o)

    Maximum and Minimum:

    static Object max(Collection coll)

    static Object max(Collection coll, Comparator comp)

    static Object min(Collection coll)

    static Object min(Collection coll, Comparator comp)

    Copystatic void copy(List dest, List src)

  • 8/14/2019 11 1 Collections and Generics

    63/67

    63Java

    Sort:

    static void sort(List list)

    static void sort(List list,Comparator c )

    Swap

    static void swap(List list, int i, int j)Reverse, Replace and Shuffle

    static void reverse(List list)

    static boolean replaceAll(List list, Object oldVal,Object newVal)

    static void shuffle(List list)

    Arrays

  • 8/14/2019 11 1 Collections and Generics

    64/67

    64Java

    Arrays Like Collections, this class also is a general utility

    class providing methods to fill, sort, search but in thiscase it works on arrays instead of a Collection

    object.

    Methods:static int binarySearch(xxx[] a,

    byte key)

    xxx: any primitive type or Object

    static int binarySearch(T[] a,

    T key, Comparator

  • 8/14/2019 11 1 Collections and Generics

    65/67

    65Java

    static void sort(xxx[] a)

    static void fill(xxx[] a, xxx val)

    static boolean equals(xxx[] a, xxx[] a2)

    xxx: any primitive type or Object

    Converting arrays into

  • 8/14/2019 11 1 Collections and Generics

    66/67

    66Java

    Converting arrays into

    Collection

    In Arrays class: From array into List

    static List asList(T... a)

    static List asList(Object[] a)For now

    Converting Collection into

  • 8/14/2019 11 1 Collections and Generics

    67/67

    Converting Collection into

    arrays

    In Collection interface: From Collection

    into array

    Object[] toArray()

    T[] toArray(T[] a)

    We will come to this at the end ofgenerics