collections print

Upload: ankitgaur36

Post on 05-Apr-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 Collections Print

    1/20

    Java Collections

    Java Collections

    Object-oriented programming

    Inf1 :: 2005

    Object-oriented programming Java Collections

    http://find/http://goback/
  • 7/31/2019 Collections Print

    2/20

    Java Collections

    Collections

    Data structures like the ones we discussed in the previouslectures are so important that the Java library provided ageneric implementation

    Package java.util

    The collections framework is a perfect example ofpolymorphism, interfaces and object-oriented design

    There is a basic interface (Collection) that all classes injava.util implementBehaviours are implemented in a variety of ways

    We will deal with lists, sets, iterators and trees

    Object-oriented programming Java Collections

    http://find/
  • 7/31/2019 Collections Print

    3/20

    Java Collections

    The class/interface hierarchy

    Collection

    boolean isEmpty ()

    boolean add/remove (Object o)boolean add/removeAll (Collection c)

    void clear ()

    boolean contains (Object o)

    boolean containsAll (Collection c)

    Iterator iterator ()

    int size ()

    Object [] toArray ()

    List

    Object get (int index)

    Object set (int index, Object o)

    void add (int index, Object o)void addAll (int index, Collection c)

    Object remove (int index)

    int indexOf (Object o)

    int lastIndexOf (Object o)

    ListIterator listIterator ()

    ListIterator listIterator (int index)

    List subList (int start, int end)

    AbstractList

    void removeRange (int start, int end)

    LinkedList

    Object getFirst ()

    Object getLast ()

    void addFirst (Object o)

    void addLast (Object o)

    Object removeFirst ()

    Object removeLast ()

    AbstractSequentialList

    ArrayList

    void ensureCapacity (int min)

    void trimToSize ()

    Iterator

    boolean hasNext ()

    Object next ()

    void remove ()

    ListIterator

    boolean hasPrevious ()

    Object previous ()

    int nextIndex ()

    int previousIndex ()

    Comparator

    int compare (Object o1, Object o2)

    Set

    SortedSet

    Comparator comparator ()

    Object first ()

    Object last ()

    SortedSet headSet (Object to)

    SortedSet tailSet (Object from)

    SortedSet subset (Object from, Object to)

    TreeSet

    AbstractSet

    HashSet

    Object-oriented programming Java Collections

    http://find/
  • 7/31/2019 Collections Print

    4/20

    Java Collections

    In more detail

    Collections are either Lists or Sets

    Lists areSequentialPossibly with duplicate valuesUnordered with respect to the values they store

    Sets are

    Unordered with respect to the valuesWithout any duplicate values

    SortedSets are

    Ordered (with respect to their values) Sets

    Iterators areA way oftraversing all values in a Collection

    ListIterators are

    Special Iterators that allow one to traverse sequentialCollections like Lists

    Object-oriented programming Java Collections

    ll

    http://find/
  • 7/31/2019 Collections Print

    5/20

    Java Collections

    Using a List

    import java.util.*;

    public class ListTest {

    private static final String colors[] = { "red", "white", "blue",

    "green", "gray", "orange", "tan", "white", "cyan","peach", "gray", "orange" };

    public ListTest () {List list = new ArrayList();

    for (int i = 0; i < colors.length; i++)list.add(colors[i]);

    System.out.print("\nList: ");

    printList(list);

    System.out.print("\nReversed List: ");

    printReversedList(list);

    System.out.print("\nList from 5, forward: ");printListFromIndex(5, list);

    System.out.print("\nList from 5, backward: ");

    printReversedListFromIndex(5, list);

    }

    import

    everything from thejava.util package (the

    collections framework)

    List interface

    make the reference aim at aclass that implements theinterface (ArrayList)

    polymorphism

    ArrayLists implementation

    of add() will be called;add() is a Collection

    method and List extendsCollection

    Object-oriented programming Java Collections

    J C ll ti

    http://find/
  • 7/31/2019 Collections Print

    6/20

    Java Collections

    Traversing a List with an Iterator

    public voidprintList (List l) {

    Iterator iter = l.iterator();

    while (iter.hasNext())System.out.print(iter.next() + " ");

    System.out.println();

    }

    public voidprintReversedList (List l) {

    ListIterator iter = l.listIterator(l.size());

    while (iter.hasPrevious())

    System.out.print(iter.previous() + " ");

    System.out.println();

    }

    iterator

    declare an Iterator over the

    List, i.e., obtain a sequential handle

    over the Lists data; iterator()

    returns a ListIterator, which is

    an Iterator

    forward scankeep scanning forward, as

    long as the Iterator

    says there are more

    elements

    list iterator

    declare a ListIterator over

    the List, since we want the

    extra functionality of scanning

    from a specific point

    backward scan

    keep scanning backwards, aslong as the ListIterator

    says there are more elements

    Object-oriented programming Java Collections

    J C ll ti

    http://find/http://goback/
  • 7/31/2019 Collections Print

    7/20

    Java Collections

    Using a List results

    import java.util.*;

    public class ListTest {

    private static final String colors[] = { "red", "white", "blue",

    "green", "gray", "orange", "tan", "white", "cyan","peach", "gray", "orange" };

    public ListTest () {

    List list = new ArrayList();

    for (int i = 0; i < colors.length; i++)

    list.add(colors[i]);

    System.out.print("\nList: ");printList(list);

    System.out.print("\nReversed List: ");

    printReversedList(list);

    System.out.print("\nList from 5, forward: ");

    printListFromIndex(5, list);

    System.out.print("\nList from 5, backward: ");

    printReversedListFromIndex(5, list);

    }

    List: red white blue green gray orange tan white cyan peach gray orange

    Reversed List: orange gray peach cyan white tan orange gray green blue white red

    List from 5, forward: orange tan white cyan peach gray orange

    List from 5, backward: gray green blue white red

    Object-oriented programming Java Collections

    Java Collections

    http://find/http://goback/
  • 7/31/2019 Collections Print

    8/20

    Java Collections

    Using a Set

    import java.util.*;

    public class SetTest {

    private static final String colors[] = { "red", "white", "blue",

    "green", "gray", "orange", "tan", "white", "cyan",

    "peach", "gray", "orange" };

    public SetTest () {

    List list = new ArrayList();

    for (int i = 0; i < colors.length; i++)list.add(colors[i]);

    System.out.print("\nArrayList: ");printCollection(list);

    Set hashSet = new HashSet(list);

    System.out.print("\nHashSet: ");

    printCollection(hashSet);}

    import

    java.util.* imports

    the Collections framework

    reference to concrete classassign a List (interface) reference

    to anArrayListconcrete class

    (that implements the interface)

    create a set from a list

    use a Set (interface) reference to a

    HashSetconcrete class (that

    implements the interface); use a list

    as the input collection

    Object-oriented programming Java Collections

    Java Collections

    http://find/
  • 7/31/2019 Collections Print

    9/20

    Java Collections

    Traversing a Set

    public voidprintCollection (Collection c) {

    Iterator iter = c.iterator();

    while (iter.hasNext())

    System.out.print(iter.next() + " ");

    System.out.println();

    }

    Collection as parameter

    this will work for both

    Lists and Sets since they

    both extendCollection

    Object-oriented programming Java Collections

    Java Collections

    http://find/
  • 7/31/2019 Collections Print

    10/20

    Java Collections

    Using s Set results

    import java.util.*;

    public class SetTest {

    private static final String colors[] = { "red", "white", "blue",

    "green", "gray", "orange", "tan", "white", "cyan","peach", "gray", "orange" };

    public SetTest () {List list = new ArrayList();

    for (int i = 0; i < colors.length; i++)list.add(colors[i]);

    System.out.print("\nArrayList: ");

    printCollection(list);

    Set hashSet = new HashSet(list);

    System.out.print("\nHashSet: ");

    printCollection(hashSet);}

    ArrayList: red white blue green gray orange tan white cyan peach gray orange

    HashSet: red cyan white tan gray green orange blue peach

    Object-oriented programming Java Collections

    Java Collections

    http://find/
  • 7/31/2019 Collections Print

    11/20

    Java Collections

    Using a SortedSet

    import java.util.*;

    public class SortedSetTest {

    private static final String names[] = { "yellow", "green","black", "tan", "grey", "white","orange", "red", "green" };

    public SortedSetTest () {SortedSet set = new TreeSet ();

    for (int i = 0; i < names.length; i++)set.add(names[i]);

    System.out.print("\nset: ");printSet(set);

    System.out.print("\nheadSet(\"orange\"): ");printSet(set.headSet("orange"));

    System.out.print("\ntailSet(\"orange\"): ");printSet(set.tailSet("orange"));

    System.out.print("\nheadSet(\"foo\"): ");printSet(set.headSet("foo"));

    System.out.print("\ntailSet(\"foo\"): ");printSet(set.tailSet("foo"));

    System.out.print("\nfirst: ");System.out.println(set.first());

    System.out.print("\nlast: ");System.out.println(set.last());

    }

    polymorphism

    TreeSetimplementsSortedSet

    SortedSetbehaviour

    the methods called are

    SortedSetmethods, but

    TreeSets implementations

    will be called

    Object-oriented programming Java Collections

    Java Collections

    http://find/
  • 7/31/2019 Collections Print

    12/20

    J

    Traversing a SortedSet through an Iterator

    public voidprintSet (SortedSet set) {Iterator iter = set.iterator();

    while (iter.hasNext())

    System.out.print(iter.next() + " ");

    System.out.println();

    }

    SortedSetreference

    though a TreeSet

    instance will bepassed as

    aparameter by the caller

    Collectionbehaviour

    a SortedSetis still a

    Collectionso we canhave an Iterator over it

    Object-oriented programming Java Collections

    Java Collections

    http://find/
  • 7/31/2019 Collections Print

    13/20

    J

    Using s SortedSet resultsimport java.util.*;

    public class SortedSetTest {

    private static final String names[] = { "yellow", "green",

    "black", "tan", "grey", "white","orange", "red", "green" };

    public SortedSetTest () {SortedSet set = new TreeSet ();

    for (int i = 0; i < names.length; i++)set.add(names[i]);

    System.out.print("\nset: ");printSet(set);

    System.out.print("\nheadSet(\"orange\"): ");printSet(set.headSet("orange"));

    System.out.print("\ntailSet(\"orange\"): ");printSet(set.tailSet("orange"));

    System.out.print("\nheadSet(\"foo\"): ");printSet(set.headSet("foo"));

    System.out.print("\ntailSet(\"foo\"): ");printSet(set.tailSet("foo"));

    System.out.print("\nfirst: ");

    System.out.println(set.first());

    System.out.print("\nlast: ");System.out.println(set.last());

    }

    set: black green grey orange red tan white yellowheadSet("orange"): black green greytailSet("orange"): orange red tan white yellowheadSet("foo"): blacktailSet("foo"): green grey orange red tan white yellowfirst: black

    last: yellow

    Object-oriented programming Java Collections

    Java Collections

    http://find/
  • 7/31/2019 Collections Print

    14/20

    Classes Arrays and Collections

    Provide generic implementations of certain functions

    Static method calls to invoke desired behaviour

    Arrays.sort(array , value)Arrays.binarySearch(array , value)Collections.sort(Collection c)

    Collections.binarySearch(Collection c , Object o)

    We will focus on Collections

    Object-oriented programming Java Collections

    Java Collections

    http://find/http://goback/
  • 7/31/2019 Collections Print

    15/20

    Sorting and searching a List

    Carried out with the aid of an object that implements theComparator interface

    Main comparison method is: int compare (Object o1,Object o2)

    Ifo1 < o2, then return a negative integerIfo1 == o2, then return zeroIfo1 > o2, then return a positive integer

    Object-oriented programming Java Collections

    Java Collections

    http://find/http://goback/
  • 7/31/2019 Collections Print

    16/20

    A Time classimport java.text.DecimalFormat;

    public class Time {

    private int hour;

    private int minute;

    private int second;

    public Time () { this(0, 0, 0); }

    public Time (int h) { this(h, 0, 0); }

    public Time (int h, int m) { this(h, m, 0); }

    public Time (int h, int m, int s) {

    setTime(h, m, s);

    }

    public voidsetTime (int h, int m, int s) {setHour(h);

    setMinute(m);

    setSecond(s);

    }

    public voidsetHour (int h) { hour = ((h >= 0 || h < 24) ? h : 0); }

    public voidsetMinute (int m) { minute = ((m >= 0 || m < 60) ? m : 0); }

    public voidsetSecond (int s) { second = ((s >= 0 || s < 60) ? s : 0); }

    public int getHour () { return hour; }

    public int getMinute () { return minute; }

    public int getSecond () { return second; }

    public String toString () {

    DecimalFormat twoDigits = new DecimalFormat("00");

    return twoDigits.format(hour) + ":"

    + twoDigits.format(minute) + ":" + twoDigits.format(second);

    }

    }

    Object-oriented programming Java Collections

    Java Collections

    http://find/http://goback/
  • 7/31/2019 Collections Print

    17/20

    A TimeComparator class

    import java.util.Comparator;

    public class TimeComparator implements Comparator {

    public TimeComparator () {}

    public int compare (Object o1, Object o2) {Time t1 = (Time) o1;

    Time t2 = (Time) o2;

    int comp = (t1.getHour() - t2.getHour());

    if (comp != 0) return comp;

    comp = (t1.getMinute() - t2.getMinute());

    if (comp != 0) return comp;

    comp = (t1.getSecond() - t2.getSecond());

    return comp;

    }

    }

    import

    simply import

    the necessaryinterface

    implementation

    specify which interface is

    implemented and provide animplementation for the methods

    of the interface

    cast

    TimeComparator can only

    handle Timeobjects; cast the

    parameters to Time (anything

    else will be a runtime error)

    comparison

    make the comparison, at all

    times abiding by the

    semantics of the interface

    Object-oriented programming Java Collections

    Java Collections

    http://find/
  • 7/31/2019 Collections Print

    18/20

    Sorting a List ofTime objects

    import java.util.*;

    public class CollectionSortTest {

    public static voidmain (String args []) {

    List list = new ArrayList();

    list.add(new Time( 6, 24, 34));

    list.add(new Time(18, 14, 5));

    list.add(new Time( 8, 05, 0));

    list.add(new Time(12, 07, 58));

    list.add(new Time( 6, 14, 22));

    System.out.print("unsorted list is: ");

    System.out.println(list);

    Collections.sort(list, new TimeComparator());

    System.out.print("sorted list is: ");

    System.out.println(list);

    }

    }

    static call

    Collections.sort()is a static method

    TimeComparator

    passed as the argument

    to sort(); becomes the

    sorting criterion

    unsorted list is: [06:24:34, 18:14:05, 08:05:00, 12:07:58, 06:14:22]

    sorted list is: [06:14:22, 06:24:34, 08:05:00, 12:07:58, 18:14:05]

    Object-oriented programming Java Collections

    Java Collections

    http://find/
  • 7/31/2019 Collections Print

    19/20

    Sorting and searching a List ofString objects

    import java.util.*;

    public class CollectionSearchTest {

    private static final String colors[] = { "red", "white", "blue",

    "green", "gray", "orange", "tan", "white", "cyan",

    "peach", "gray", "orange" };

    public staticvoidmain (String args []) {

    List list = new ArrayList();

    for (int i = 0; i < colors.length; i++)

    list.add(colors[i]);

    System.out.println("unsorted list: " + list);

    Collections.sort(list);

    System.out.println("sorted list: " + list);

    int p = Collections.binarySearch(list, "gray");

    System.out.println("gray first appears in position: " + p);

    p = Collections.binarySearch(list, "maroon");

    System.out.println("maroon first appears in position: " + p);

    }

    }

    no need for aComparator

    the class of the objectsinserted

    in the list (String), already

    implements the Comparator

    interface

    unsorted list: [red, white, blue, green, gray, orange, tan, white, cyan, peach, gray, orange]

    sorted list: [blue, cyan, gray, gray, green, orange, orange, peach, red, tan, white, white]

    gray first appears in position: 2

    maroon first appears in position: -6

    Collections.binarySearch()

    pass a list and the object were

    looking for and were done!

    Object-oriented programming Java Collections

    Java Collections

    http://find/
  • 7/31/2019 Collections Print

    20/20

    Things to do

    To do

    Read Deitel & Deitel, Sections 22.1, 22.2, 22.4, 22.5, 22.7

    Become accustomed with the Java Collections framework

    Spend some time thinking on the differences between thevarious interfaces and classes

    Object-oriented programming Java Collections

    http://find/http://goback/