Presentation is loading. Please wait.

Presentation is loading. Please wait.

Algorithm Programming 2 89-211 Containers in Java Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

Similar presentations


Presentation on theme: "Algorithm Programming 2 89-211 Containers in Java Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko."— Presentation transcript:

1 Algorithm Programming 2 89-211 Containers in Java Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko

2 Array utilities In “ java.utils.Arrays ” class there are some static utility functions: List asList(Object[] a) ; boolean equals(char[] a, char[] b) boolean equals(Object[] a, Object[] b) void fill(char[] a, char val) void fill(Object[] a, Object val) void fill(char[] a, int fromIdx, int toIdx, char val) void fill(Object[] a, int fromIdx, int toIdx, Object val)

3 Array Utilities int binarySearch(char[] a, char key) int binarySearch(Object[] a, Object key) int binarySearch(Object[] a, Object key, Comparator c) void sort(char[] a) void sort(Object[] a) void sort(Object[] a, Comparator c) void sort(char[] a, int fromIdx, int toIdx) void sort(Object[] a, int fromIdx, int toIdx) void sort(Object[] a, int fromIdx, int toIdx, Comparator c)

4 Array Utilities For sort and binarySearch of Objects Either a new Comparator c must be given Or the given objects must implement Comparable In both cases the comparison function returns Less then 0, if left object is smaller Greater then 0, if left object is greater 0, if both objects are equal In java.utils.Comparator interface Comparator { int compare(Object o1, Object o2) ; } In java.lang.Comparable interface Comparable { int compareTo(Object o) ; }

5 Design Pattern : “ STRATEGY ” “ Strategy ” Pattern: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Example: Arrays.sort(Object[] a, Comparator c) binarySearch(Object[] a, Object key, Comparator c)

6 Example : sort() import java.util.* ; class A { public final int i ; A(int i) { this.i = i ; } } class Ascending implements Comparator { public int compare(Object o1, Object o2) { A a1=(A)o1, a2=(A)o2 ; if (a1.i<a2.i) return -1 ; if (a1.i>a2.i) return +1 ; return 0 ; } } class Descending implements Comparator { public int compare(Object o1, Object o2) { A a1=(A)o1, a2=(A)o2 ; if (a1.i<a2.i) return +1 ; if (a1.i>a2.i) return -1 ; return 0 ; } }

7 Example “ sort() ” public class S { public static void main(String[] args) { A[] asc = { new A(1), new A(5), new A(3), new A(2) } ; A[] dsc = (A[]) asc.clone() ; Arrays.sort(asc,new Ascending()) ; Arrays.sort(dsc,new Descending()) ; System.out.println("Ascending : "+arrStr(asc)) ; System.out.println("Descending: "+arrStr(dsc)) ; } static String arrStr(A[] a) { String s = "[" + a[0].i ; for (int i=1;i<a.length;++i) s += ","+a[i].i ; s+="]" ; return s ; } // Output : Ascending : [1,2,3,5] //Descending: [5,3,2,1]

8 Java Containers In Java two types of Containers Collection : A group of individual elements List : Keeps elements in a particular sequence. Set : Cannot have duplicate elements Map : A set of key-value pairs. ( Also known as Associative arrays)

9 Simplified Collections Diagram

10 Collection methods boolean add(Object o) : Adds element to the collection boolean add(Collection c) : void clear() : Clears the collection. Size will be 0. boolean contains(Object o) : boolean containsAll(Collection c) : boolean isEmpty() : Returns true if collection is empty. Iterator iterator() : boolean remove(Object o) : Removes the element. boolean removeAll(Collection c) : boolean retainAll(Collection c) : int size() : Returns the number of elements in collection Object[] toArray() : Object[] toArray(Object[] a) :

11 List and Set implementations “ Collection ” interface “ List ” interface : ( Order of insertion is kept ) ArrayList : Implemented as an array of elements. Fast Random Access, but slow insertion and deletion from the middle. LinkedList : Implemented as a double linked list. Insertion and Deletion in the middle is fast, but Slow in Random Access. “ Set ” interface : ( Unique elements ) HashSet : For sets where look-up time is important. Inserted objects must implement hashCode() method. TreeSet : A sorted list can easily be extracted

12 List and Set methods interface “ List ” : Addition to “ Collection ” Object get(int index) Object set(int index, Object element) void add(int index, Object element) Object remove(int index) int indexOf(Object o) … Interface “ Set ” : Addition to “ Collection ” …

13 Map methods Object put(Object key, Object value) : Adds key-value pair to map void putAll(Map t) : Object get(Object key) : Get the value for the given key void clear() : Clears the map. Size will be 0. boolean containsKey(Object key) : Checks if the key exists. boolean containsValue(Object value) : boolean isEmpty() : Returns true if map is empty Object remove(Object key) : Removes the key from map int size() : Returns the number of elements in the map Set entrySet() : Set keySet() : Collection values() :

14 Map implementations “ Map ” interface HashMap : Implemented using hash tables. Key objects must implement hashCode() method. LinkedHashMap : Like HashMap., but keeps the order of insertion TreeMap : Implemented by a red-black tree. You get the results in sorted order. (Determined by Comparable or Comparator)

15 Iterator Pattern Intent Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. Motivation An aggregate object such as a list should give you a way to access its elements without exposing its internal structure. Moreover you might want to traverse the list in different ways. We cannot fill the List interface with different traversals we can need. We may want a couple of traversals pending on the same time.

16 Iterator

17 Iterator – Example Structure

18 Iterator Use iterator pattern … To access an aggregate object ’ s contents without exposing its internal representation. To support multiple traversals of aggregate objects. To provide a uniform interface for traversing different aggregate structures (to support polymorphic iteration).

19 Iterator – General Structure

20 Iterator Participants Iterator Defines an interface for accessing and traversing elements ConcreteIterator Implements the iterator interface Keeps track of the current position in the traversal Aggregate Defines an interface method that creates an iterator object ConcreteAggregate Implements the iterator creation method, and returns an instance of the proper ConcreteIterator

21 Iterator Consequences It supports variants in the traversal of an aggregate Iterators simplify the Aggregate interface More then one traversal can be pending on an aggregate Implementation Who controls the iteration? Client controls the iteration. (called External Iterator) Iterator controls the iteration. (called Internal Iterator) Who defines the traversal algorithm? The aggregate: This is called a cursor. The iterator. How robust is the iterator? Modifying an aggregate while traversing it will be dangerous for iterator. Robust iterator will not be effected by changes.

22 Java Iterators interface Collection { … Iterator iterator(); … } interface Set extends Collection { … Iterator iterator(); … } interface List extends Collection { … Iterator iterator(); ListIterator listIterator(); ListIterator listIterator(int index); … } Interface Iterator { boolean hasNext() ; Object next() ; void remove() ; } Interface ListIterator extends Iterator { boolean hasNext() ; Object next() ; boolean hasPrevious() ; Object previous() ; int nextIndex() ; int previousIndex() ; void remove() ; void set(Object o) ; void add(Object o) ; }

23 Java Iterator Example import java.util.*; public class IteratorExample { public static void main(String[] args) { List ints = new ArrayList(); for(int i = 0; i < 10; i++) ints.add(new Integer(i)); Iterator e = ints.iterator(); while(e.hasNext()) System.out.println(((Integer)e.next()).intValue()); }


Download ppt "Algorithm Programming 2 89-211 Containers in Java Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko."

Similar presentations


Ads by Google