Topics• What is and Why Collections?• Core Collection Interfaces• Implementations• Algorithms• Custom Implementations• Int...
What is a Collection?• A “collection” object — sometimes called a container— is simply an object that groups multiple elem...
What is a Collection Framework?• A collections framework is a unified architecture forrepresenting and manipulating collec...
Benefits of Collection Framework• Reduces programming effort• Increases program speed and quality• Allows interoperability...
Interfacesandimplementationin Collection FrameworkTheAndroid-mania.com
Interfaces• Collection interfaces are abstract data types thatrepresent collections> Collection interfaces are in the form...
Implementations• These are the concrete implementations of the collectioninterfaces.TheAndroid-mania.com
Types of Implementations• General-purpose implementations• Special-purpose implementations• Concurrent implementations• Wr...
Implementations• Implementations are the data objects used to storecollections, which implement the interfaces• Each of th...
General Purpose Implementationsinterfaces ImplementationsHash Table ResizableArrayTree Linked List HashTbale+ Linked ListS...
Algorithms• These are the methods that perform usefulcomputations, such as searching and sorting, onobjects that implement...
Core Collection interfacesTheAndroid-mania.com
Core Collection Interfaces HierarchyCollectionSet List QueueSortedSetMapSorted MapTheAndroid-mania.com
Core Collection Interfaces• Core collection interfaces are the foundation of theJava Collections Framework• Core collectio...
“Collection” interfaceTheAndroid-mania.com
“Collection” Interface• The root of the collection hierarchy• Is the least common denominator that all collectionimplement...
“Collection” Interface (Java SE 5)public interface Collection<E> extends Iterable<E> {// Basic operationsint size();boolea...
Example import java.util.*; import java.util.Collection; public class collectioninterface { public static void main(St...
add() and remove() methods ofCollection Interface• The add() method is defined generally enough sothat it makes sense for ...
CollectionInterfaceTraversingTheAndroid-mania.com
Two Schemes of TraversingCollections• for-each> The for-each construct allows you to concisely traverse acollection or arr...
IteratorIterator means an Object with which we can travel all through a rangeof elements.It works like a Pointer. In datab...
Iterator Interfacepublic interface Iterator {boolean hasNext();Object next();void remove(); //optional}• hasNext() method ...
Use Iterator over for-each when you needto• Remove the current element> The for-each construct hides the iterator, so you ...
List Iterator InterfaceList iterator is an interface that contains methods to retrieve theelements from a collection objec...
List InterfacesandImplementationTheAndroid-mania.com
“List” Interface• An ordered collection (sometimes called asequence)• Lists can contain duplicate elements• The user of a ...
Additional Operations Supported by“List” Interface over “Collection”• Positional access — manipulates elements basedon the...
“List” Interfacepublic interface List<E> extends Collection<E> {// Positional accessE get(int index);E set(int index, E el...
Implementations of “List” Interface• ArrayList> Offers constant-time positional access> Fast> Think of ArrayList as Vector...
“Array List”ArrayList is a Sub class of AbstractList and implements List.Signature:Array List includes a feature called Dy...
Array List Examplesimport java.util.*;public class IteratorArrayList{public static void main(String args[]){ArrayList al=n...
Linked ListA linked List contains a group of elements in the form of nodes.Each node will have 3 fieldsData Field contains...
Set InterfaceandImplementationTheAndroid-mania.com
“Set” Interface• A collection that cannot contain duplicate elements• Models the mathematical set abstraction and is usedt...
“Set” Interface (Java SE 5)public interface Set<E> extends Collection<E> {// Basic operationsint size();boolean isEmpty();...
“Sorted Set” Interface• A Set that maintains its elements in ascending order.Several additional operations are provided to...
Implementations of “Set”InterfaceImplementations of “Set” Interface• HashSet• TreeSet• LinkedHashSetTheAndroid-mania.com
HashSet• HashSet is much faster than TreeSet (constant time versus log-timefor most operations) but offers no ordering gua...
Example for HashSetimport java.util.*;public class HashSetinfo{public static void main(String args[]){HashSet hs=new HashS...
TreeSet• When you need to use the operations in the SortedSet interface, or ifvalue-ordered iteration is required.This cla...
Example: Set Interface & TreeSetImport java.util.*;Public Class TreeSet{public static void main(String[] args) {Set ts = n...
LinkedHashSet• Implemented as a hash table with a linked list running through it• Provides insertion-ordered iteration (le...
Example: Set Interface & LinkedHashSetImport java.util.*;public class LinkedHashSet{public static void main(String[] args)...
Example: Set Interface & HashSetpublic class Main {public static void main(String[] args) {Set s = new HashSet(); // Order...
Example: Set Interface & HashSetThe numbers are added in the following order23412Set type = java.util.HashSet [3, 2, 4, 1]...
Map interfaceandImplementationTheAndroid-mania.com
“Map” Interface• Handles key/value pairs.• A Map cannot contain duplicate keys; eachkey can map to at most one value.If y...
“Map” Interface (Java SE 5)public interface Map<K,V> {// Basic operationsV put(K key, V value);V get(Object key);V remove(...
“Sorted Map” Interface• A Map that maintains its mappings in ascending keyorder> This is the Map analog of Sorted Set.• So...
Implementations of “Map” Interface• Hash Map> Use it you want maximum speed and dont care about iterationorder.> Most comm...
Hash MapHashMap is like Hashtable which stores key/value pairs. It implementsmap interface and we can use all the operatio...
Tree mapThis class extends AbstractMap and implements SortedMap.This class Guarantees that the elements will be in ascendi...
Queue interfaceandimplementationTheAndroid-mania.com
“Queue” Interface• A collection used to hold multiple elements prior toprocessing• Besides basic Collection operations, a ...
Implementations of QueueInterface• General purpose Queue implementations> LinkedList implements the Queue interface, provi...
Convenience ImplementationsTheAndroid-mania.com
Collections Class• Provides methods to return the empty Set, List, andMap — emptySet, emptyList, and emptyMap.> The main u...
Abstract ClassesTheAndroid-mania.com
Abstract Classes• Includes abstract implementations> AbstractCollection> AbstractSet> AbstractList> AbstractSequentialList...
AlgorithmsTheAndroid-mania.com
Algorithms• Sorting• Shuffling• Routine data manipulation• Searching• Composition• Find extreme valuesTheAndroid-mania.com
Algorithms• Provided as static methods of Collections class• The first argument is the collection on which theoperation is...
Sorting• The sort algorithm reorders a List so that itselements are in ascending order according to anordering relationshi...
Natural Ordering• The type of the elements in a List already implementsComparable interface• Examples> If the List consist...
Sorting by Natural Order of List// Set up test dataString n[] = {new String("John"),new String("Karl"),new String("Groucho...
Sorting by ComparatorInterface• A comparison function, which imposes a totalordering on some collection of objects• Compar...
Sorting by Natural Order of List// Set up test dataArrayList u2 = new ArrayList();u2.add("Beautiful Day");u2.add("Stuck In...
Shuffling• The shuffle algorithm does the opposite of what sort does, destroyingany trace of order that may have been pres...
Routine Data Manipulation• The Collections class provides five algorithms for doing routine datamanipulation on List objec...
Searching• The Collections class has binarySearch() method forsearching a specified element in a sorted List// Set up test...
Composition• Collections.frequency(l) — counts the number oftimes the specified element occurs in the specifiedcollection•...
Upcoming SlideShare
Loading in...5
×

Collections

704

Published on

Published in: Education, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
704
On Slideshare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
14
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • 5/15/2013 TheAndroid-mania.com
  • Collections

    1. 1. Topics• What is and Why Collections?• Core Collection Interfaces• Implementations• Algorithms• Custom Implementations• InteroperabilityTheAndroid-mania.com
    2. 2. What is a Collection?• A “collection” object — sometimes called a container— is simply an object that groups multiple elementsinto a single unit.• Collections are used to store, retrieve, manipulate,and communicate aggregate data> Typically, they represent data items that form a natural group,such as a poker hand (a collection of cards), a mail folder (acollection of letters), or a telephone directory (a mapping ofnames to phone numbers).TheAndroid-mania.com
    3. 3. What is a Collection Framework?• A collections framework is a unified architecture forrepresenting and manipulating collections• All collections frameworks contain the following:> Interfaces> Implementations> AlgorithmsTheAndroid-mania.com
    4. 4. Benefits of Collection Framework• Reduces programming effort• Increases program speed and quality• Allows interoperability among unrelated APIs> The collection interfaces are the vernacular by which APIspass collections back and forth• Reduce effort to learn and use new APIs• Reduces effort to design new APIs• Fosters software reuse> New data structures that conform to the standard collectioninterfaces are by nature reusableTheAndroid-mania.com
    5. 5. Interfacesandimplementationin Collection FrameworkTheAndroid-mania.com
    6. 6. Interfaces• Collection interfaces are abstract data types thatrepresent collections> Collection interfaces are in the form of Java interfaces• Interfaces allow collections to be manipulatedindependently of the implementation details of theirrepresentation> Polymorphic behavior• In Java programming language (and other objectoriented languages),interfaces generally form ahierarchy> You choose one that meets your need as a typeTheAndroid-mania.com
    7. 7. Implementations• These are the concrete implementations of the collectioninterfaces.TheAndroid-mania.com
    8. 8. Types of Implementations• General-purpose implementations• Special-purpose implementations• Concurrent implementations• Wrapper implementations• Convenience implementations• Abstract implementationsTheAndroid-mania.com
    9. 9. Implementations• Implementations are the data objects used to storecollections, which implement the interfaces• Each of the general-purpose implementations (youwill see in the following slide) provides all optionaloperations contained in its interface• Java Collections Framework also provides severalspecial-purpose implementations for situations thatrequire nonstandard performance, usagerestrictions, or other unusual behaviorTheAndroid-mania.com
    10. 10. General Purpose Implementationsinterfaces ImplementationsHash Table ResizableArrayTree Linked List HashTbale+ Linked ListSet Hash Set Tree Set Linked HashSetList Array List Linked ListQueueMap Hash Map Tree Map Linked HashMapTheAndroid-mania.com
    11. 11. Algorithms• These are the methods that perform usefulcomputations, such as searching and sorting, onobjects that implement collection interfaces• The algorithms are said to be polymorphic: that is,the same method can be used on many differentimplementations of the appropriate collectioninterface> In essence, algorithms are reusable functionality.TheAndroid-mania.com
    12. 12. Core Collection interfacesTheAndroid-mania.com
    13. 13. Core Collection Interfaces HierarchyCollectionSet List QueueSortedSetMapSorted MapTheAndroid-mania.com
    14. 14. Core Collection Interfaces• Core collection interfaces are the foundation of theJava Collections Framework• Core collection interfaces form a inheritancehierarchy among themselves> You can create a new Collection interface from them (highly likelyyou dont have to)TheAndroid-mania.com
    15. 15. “Collection” interfaceTheAndroid-mania.com
    16. 16. “Collection” Interface• The root of the collection hierarchy• Is the least common denominator that all collectionimplement> Every collection object is a type of Collection interface• Is used to pass collection objects around and tomanipulate them when maximum generality isdesired> Use Collection interface as a type• JDK doesnt provide any direct implementations ofthis interface but provides implementations of morespecific sub interfaces, such as Set and List.TheAndroid-mania.com
    17. 17. “Collection” Interface (Java SE 5)public interface Collection<E> extends Iterable<E> {// Basic operationsint size();boolean isEmpty();boolean contains(Object element);boolean add(E element); //optionalboolean remove(Object element); //optionalIterator<E> iterator();// Bulk operationsboolean containsAll(Collection<?> c);boolean addAll(Collection<? extends E> c); //optionalboolean removeAll(Collection<?> c); //optionalboolean retainAll(Collection<?> c); //optionalvoid clear(); //optional// Array operationsObject[] toArray(); TheAndroid-mania.com
    18. 18. Example import java.util.*; import java.util.Collection; public class collectioninterface { public static void main(String[] args) { Collection collection = new ArrayList(); collection.add("Dev"); collection.add("Manuals"); System.out.print(" Elements Of the Array List are "); System.out.print(collection + "."); } }TheAndroid-mania.com
    19. 19. add() and remove() methods ofCollection Interface• The add() method is defined generally enough sothat it makes sense for collections that allowduplicates as well as those that dont• It guarantees that the Collection will contain thespecified element after the call completes, andreturns true if the Collection changes as a result ofthe call.> add() method of Set interface follows “no duplicate” ruleTheAndroid-mania.com
    20. 20. CollectionInterfaceTraversingTheAndroid-mania.com
    21. 21. Two Schemes of TraversingCollections• for-each> The for-each construct allows you to concisely traverse acollection or array using a for loopfor (Object o: collection)System.out.println(o);• Iterator> An Iterator is an object that enables you to traverse through acollection and to remove elements from the collectionselectively, if desiredTheAndroid-mania.com
    22. 22. IteratorIterator means an Object with which we can travel all through a rangeof elements.It works like a Pointer. In database, Sometimes Iterator is called aCursor.Class signature : Public interface IteratorEnumeration interface is replaced by iterator in collections framework.the advantages over Enumerations:Iterator allow the caller to remove elements from the underlyingcollection during the iteration with well-defined semantics.Method name have been improved.We can print from any index number , but need not all the elements.TheAndroid-mania.com
    23. 23. Iterator Interfacepublic interface Iterator {boolean hasNext();Object next();void remove(); //optional}• hasNext() method returns true if the iteration has more elements• next() method returns the next element in the iteration• remove() is the only safe way to modify a collection duringiteration; the behavior is unspecified if the underlying collection ismodified in any other way while the iteration is in progressTheAndroid-mania.com
    24. 24. Use Iterator over for-each when you needto• Remove the current element> The for-each construct hides the iterator, so you cannot callremove> Therefore, the for-each construct is not usable for filtering.static void filter(Collection<?> c) {for (Iterator<?> it = c.iterator(); it.hasNext(); )if (!cond(it.next()))it.remove();}• Iterate over multiple collections in parallelTheAndroid-mania.com
    25. 25. List Iterator InterfaceList iterator is an interface that contains methods to retrieve theelements from a collection object, both in forward and reversedirections.It has following methods:boolean hasNext(); returns true if the List Iterator has more elements whentraversing the list in the forward direction.boolean hasPrevious(); returns true if the List Iterator has more elements whentraversing the list in the reverse direction.element next(); returns the next element.element previous(); returns the previous element in the list.void remove(); removes from the list the last element that was returned.TheAndroid-mania.com
    26. 26. List InterfacesandImplementationTheAndroid-mania.com
    27. 27. “List” Interface• An ordered collection (sometimes called asequence)• Lists can contain duplicate elements• The user of a List generally has precise control overwhere in the list each element is inserted and canaccess elements by their integer index (position)> If youve used Vector, youre already familiar with the general basicsof ListTheAndroid-mania.com
    28. 28. Additional Operations Supported by“List” Interface over “Collection”• Positional access — manipulates elements basedon their numerical position in the list• Search — searches for a specified object in the listand returns its numerical position• Iteration — extends Iterator semantics to takeadvantage of the lists sequential nature• Range-view — performs arbitrary range operationson the list.TheAndroid-mania.com
    29. 29. “List” Interfacepublic interface List<E> extends Collection<E> {// Positional accessE get(int index);E set(int index, E element); //optionalboolean add(E element); //optionalvoid add(int index, E element); //optionalE remove(int index); //optionalboolean addAll(int index,Collection<? extends E> c); //optional// Searchint indexOf(Object o);int lastIndexOf(Object o);// IterationListIterator<E> listIterator();ListIterator<E> listIterator(int index);// Range-view TheAndroid-mania.com
    30. 30. Implementations of “List” Interface• ArrayList> Offers constant-time positional access> Fast> Think of ArrayList as Vector without the synchronizationoverhead> Most commonly used implementation• LinkedList> Use it you frequently add elements to the beginning of the Listor iterate over the List to delete elements from its interiorTheAndroid-mania.com
    31. 31. “Array List”ArrayList is a Sub class of AbstractList and implements List.Signature:Array List includes a feature called Dynamic Arrays-memory isdynamically allotted and re-allotted to accommodate all theelements.Array list is not Synchronised.public class ArrayList extends AbstractList implements List, Cloneable,SerializableTheAndroid-mania.com
    32. 32. Array List Examplesimport java.util.*;public class IteratorArrayList{public static void main(String args[]){ArrayList al=new ArrayList();al.add(new Integer(10));al.add(new Double(25.5));al.add(new Boolean(false));al.add(new String("santhosh"));al.add(new StringBuffer("Trainer"));al.add(new Date());Iterator it=al.iterator();while(it.hasNext()){Object obj=it.next();System.out.println(obj);if(obj instanceof Number){it.remove();}} TheAndroid-mania.com
    33. 33. Linked ListA linked List contains a group of elements in the form of nodes.Each node will have 3 fieldsData Field contains dataAndthe two Link fields contain references to previous and next nodes.Linked List is very convenient to store data. Inserting the elementsinto the linked list and removing the elements from the linked list isdone quickly and takes the same amount of time.TheAndroid-mania.com
    34. 34. Set InterfaceandImplementationTheAndroid-mania.com
    35. 35. “Set” Interface• A collection that cannot contain duplicate elements• Models the mathematical set abstraction and is usedto represent sets> cards comprising a poker hand> courses making up a students schedule> the processes running on a machine• The Set interface contains only methods inheritedfrom Collection and adds the restriction thatduplicate elements are prohibited.TheAndroid-mania.com
    36. 36. “Set” Interface (Java SE 5)public interface Set<E> extends Collection<E> {// Basic operationsint size();boolean isEmpty();boolean contains(Object element);boolean add(E element); //optionalboolean remove(Object element); //optionalIterator<E> iterator();// Bulk operationsboolean containsAll(Collection<?> c);boolean addAll(Collection<? extends E> c); //optionalboolean removeAll(Collection<?> c); //optionalboolean retainAll(Collection<?> c); //optionalvoid clear(); //optional// Array OperationsObject[] toArray(); TheAndroid-mania.com
    37. 37. “Sorted Set” Interface• A Set that maintains its elements in ascending order.Several additional operations are provided to takeadvantage of the ordering• Sorted sets are used for naturally ordered sets, suchas word lists and membership roll.TheAndroid-mania.com
    38. 38. Implementations of “Set”InterfaceImplementations of “Set” Interface• HashSet• TreeSet• LinkedHashSetTheAndroid-mania.com
    39. 39. HashSet• HashSet is much faster than TreeSet (constant time versus log-timefor most operations) but offers no ordering guarantees• Mostly commonly used implementation.Caveats of Using HashSet• Iteration is linear in the sum of the number of entries and the numberof buckets (the capacity).> Choosing an initial capacity thats too high can waste bothspace and time.> Choosing an initial capacity thats too low wastes time by copying thedata structure each time its forced to increase its capacity.TheAndroid-mania.com
    40. 40. Example for HashSetimport java.util.*;public class HashSetinfo{public static void main(String args[]){HashSet hs=new HashSet();Integer il=new Integer(10);hs.add(il);Double d1=new Double(10.5);hs.add(d1);hs.add(new Integer(20));hs.add("Santhosh Teleman");hs.add(new String("Trainer"));System.out.println("Number of elements"+hs.size());System.out.println("il exists:"+hs.contails(il));System.out.println("Elements before remeoval");System.out.println(hs);hs.remove(d1);System.out.println("elements after remeoval");System.out.println(hs);TheAndroid-mania.com
    41. 41. TreeSet• When you need to use the operations in the SortedSet interface, or ifvalue-ordered iteration is required.This class guarantees that the sorted set will be in ascending elementorder,sorted according to to the natural order of the elements.To optimize TreeSet and HashSet space usage, we can start with lessinitial capacity and load capacity.Class Signature:public class TreeSet extends AbstractSet implements SortedSet ,Cloneable,SerializableTheAndroid-mania.com
    42. 42. Example: Set Interface & TreeSetImport java.util.*;Public Class TreeSet{public static void main(String[] args) {Set ts = new TreeSet();ts.add("one");ts.add("two");ts.add("three");ts.add("four");ts.add("three");System.out.println("Members from TreeSet = " + ts);}Result: Members from TreeSet = [four, one, three, two]TheAndroid-mania.com
    43. 43. LinkedHashSet• Implemented as a hash table with a linked list running through it• Provides insertion-ordered iteration (least recently inserted to mostrecently) and runs nearly as fast as HashSet.• Spares its clients from the unspecified, generally chaotic orderingprovided by HashSet without incurring the increased cost associatedwith TreeSet.TheAndroid-mania.com
    44. 44. Example: Set Interface & LinkedHashSetImport java.util.*;public class LinkedHashSet{public static void main(String[] args) {Set ts2 = new LinkedHashSet();ts2.add(2);ts2.add(1);ts2.add(3);ts2.add(3);System.out.println("Members from LinkedHashSet = " + ts2);}}Result: Members from LinkedHashSet = [2, 1, 3]TheAndroid-mania.com
    45. 45. Example: Set Interface & HashSetpublic class Main {public static void main(String[] args) {Set s = new HashSet(); // Order is not guaranteedMyOwnUtilityClass.checkDuplicate(s, args);s = new TreeSet(); // Order according to valuesMyOwnUtilityClass.checkDuplicate(s, args);s = new LinkedHashSet(); // Order according to insertionMyOwnUtilityClass.checkDuplicate(s, args);}}TheAndroid-mania.com
    46. 46. Example: Set Interface & HashSetThe numbers are added in the following order23412Set type = java.util.HashSet [3, 2, 4, 1]Set type = java.util.TreeSet [1, 2, 3, 4]Set type = java.util.LinkedHashSet [2, 3, 4, 1]TheAndroid-mania.com
    47. 47. Map interfaceandImplementationTheAndroid-mania.com
    48. 48. “Map” Interface• Handles key/value pairs.• A Map cannot contain duplicate keys; eachkey can map to at most one value.If youve used Hash table, youre alreadyfamiliar with the basics of Map.Class Signature:public interface mapTheAndroid-mania.com
    49. 49. “Map” Interface (Java SE 5)public interface Map<K,V> {// Basic operationsV put(K key, V value);V get(Object key);V remove(Object key);boolean containsKey(Object key);boolean containsValue(Object value);int size();boolean isEmpty();// Bulk operationsvoid putAll(Map<? extends K, ? extends V> m);void clear();// Collection Viewspublic Set<K> keySet();public Collection<V> values();public Set<Map.Entry<K,V>> entrySet();// Interface for entrySet elementspublic interface Entry {TheAndroid-mania.com
    50. 50. “Sorted Map” Interface• A Map that maintains its mappings in ascending keyorder> This is the Map analog of Sorted Set.• Sorted maps are used for naturally orderedcollections of key/value pairs, such as dictionariesand telephone directories.TheAndroid-mania.com
    51. 51. Implementations of “Map” Interface• Hash Map> Use it you want maximum speed and dont care about iterationorder.> Most commonly used implementation• Tree Map> Use it when you need Sorted Map operations or key-orderedCollection-view iteration• Linked HashMap> Use if you want near-Hash Map performance and insertion orderiterationTheAndroid-mania.com
    52. 52. Hash MapHashMap is like Hashtable which stores key/value pairs. It implementsmap interface and we can use all the operations (methods) of mapinterface.It permits null values and the null key.Hash map is almost equivalent to HashTable, except that it is un-synchronised and permits nulls.Order of elements is not guaranteed.Class signature:public class Hashmap extends AbstractMap implementsMap,Cloneable,SerializableTheAndroid-mania.com
    53. 53. Tree mapThis class extends AbstractMap and implements SortedMap.This class Guarantees that the elements will be in ascending key order,sorted according to the natural order based on the keys.Class signature:public class Treemap extends AbstractMap implements SortedMap ,Cloneable, SerializableTheAndroid-mania.com
    54. 54. Queue interfaceandimplementationTheAndroid-mania.com
    55. 55. “Queue” Interface• A collection used to hold multiple elements prior toprocessing• Besides basic Collection operations, a Queueprovides additional insertion, extraction, andinspection operations• Typically, but do not necessarily, order elements in aFIFO (first-in, first-out) manner.TheAndroid-mania.com
    56. 56. Implementations of QueueInterface• General purpose Queue implementations> LinkedList implements the Queue interface, providing FIFOqueue operations for add, poll, and so on> PriorityQueue class is a priority queue based on the heapdata structure> This queue orders elements according to an order specified atconstruction time, which can be the elements natural orderingor the ordering imposed by an explicit Comparator.• Concurrent Queue implementationsTheAndroid-mania.com
    57. 57. Convenience ImplementationsTheAndroid-mania.com
    58. 58. Collections Class• Provides methods to return the empty Set, List, andMap — emptySet, emptyList, and emptyMap.> The main use of these constants is as input to methods thattake a Collection of values when you dont want to provideany values at all> tourist.declarePurchases(Collections.emptySet());• Provides methods for sorting and shuffling> Collections.sort(l);> Collections.shuffle(l);TheAndroid-mania.com
    59. 59. Abstract ClassesTheAndroid-mania.com
    60. 60. Abstract Classes• Includes abstract implementations> AbstractCollection> AbstractSet> AbstractList> AbstractSequentialList> AbstractMap• To aid in custom implementations> Reduces code you have to writeTheAndroid-mania.com
    61. 61. AlgorithmsTheAndroid-mania.com
    62. 62. Algorithms• Sorting• Shuffling• Routine data manipulation• Searching• Composition• Find extreme valuesTheAndroid-mania.com
    63. 63. Algorithms• Provided as static methods of Collections class• The first argument is the collection on which theoperation is to be performed• The majority of the algorithms provided by the Javaplatform operate on List instances, but a few of themoperate on arbitrary Collection instancesTheAndroid-mania.com
    64. 64. Sorting• The sort algorithm reorders a List so that itselements are in ascending order according to anordering relationship• Two forms of the operations> takes a List and sorts it according to its elements naturalordering> takes a Comparator in addition to a List and sorts theelements with the ComparatorTheAndroid-mania.com
    65. 65. Natural Ordering• The type of the elements in a List already implementsComparable interface• Examples> If the List consists of String elements, it will be sorted intoalphabetical order> If it consists of Date elements, it will be sorted into chronologicalorder> String and Date both implement the Comparable interface.Comparable implementations provide a natural ordering for a class,which allows objects of that class to be sorted automatically• If you try to sort a list, the elements of which do notimplement Comparable, Collections.sort(list) will throw aClassCastException.TheAndroid-mania.com
    66. 66. Sorting by Natural Order of List// Set up test dataString n[] = {new String("John"),new String("Karl"),new String("Groucho"),new String("Oscar")};// Create a List from an arrayList l = Arrays.asList(n);// Perform the sorting operationCollections.sort(l);TheAndroid-mania.com
    67. 67. Sorting by ComparatorInterface• A comparison function, which imposes a totalordering on some collection of objects• Comparators can be passed to a sort method (suchas Collections.sort or Arrays.sort) to allow precisecontrol over the sort order• Comparators can also be used to control the orderof certain data structures (such as sorted sets orsorted maps), or to provide an ordering forcollections of objects that dont have a naturalOrdering.TheAndroid-mania.com
    68. 68. Sorting by Natural Order of List// Set up test dataArrayList u2 = new ArrayList();u2.add("Beautiful Day");u2.add("Stuck In A Moment You Cant Get Out Of");u2.add("Elevation");u2.add("Walk On");u2.add("Kite");u2.add("In A Little While");u2.add("Wild Honey");u2.add("Peace On Earth");u2.add("When I Look At The World");u2.add("New York");u2.add("Grace");Comparator comp = Comparators.stringComparator();Collections.sort(u2, comp); TheAndroid-mania.com
    69. 69. Shuffling• The shuffle algorithm does the opposite of what sort does, destroyingany trace of order that may have been present in a List> That is, this algorithm reorders the List based on input from asource of randomness such that all possible permutations occur withequal likelihood, assuming a fair source of randomness• Useful in implementing games of chance> could be used to shuffle a List of Card objects representing adeck> generating test casesTheAndroid-mania.com
    70. 70. Routine Data Manipulation• The Collections class provides five algorithms for doing routine datamanipulation on List objects> reverse — reverses the order of the elements in a List.> fill — overwrites every element in a List with the specified value.This operation is useful for reinitializing a List.> copy — takes two arguments, a destination List and a source List, and copiesthe elements of the source into the destination, overwriting its contents. Thedestination List must be at least as long as the source. If it is longer, theremaining elements in the destination List are unaffected.> swap — swaps the elements at the specified positions in a List.> addAll — adds all the specified elements to a Collection. The elements to beadded may be specified individually or as an array.TheAndroid-mania.com
    71. 71. Searching• The Collections class has binarySearch() method forsearching a specified element in a sorted List// Set up testing dataString name[] = {new String("Sang"),new String("Shin"),new String("Boston"),new String("Passion"),new String("Shin"),};List l = Arrays.asList(name);int position = Collections.binarySearch(l, "Boston");System.out.println("Position of the searched item = " + position);TheAndroid-mania.com
    72. 72. Composition• Collections.frequency(l) — counts the number oftimes the specified element occurs in the specifiedcollection• Collections.disjoint(l1, l2) — determines whether twoCollections are disjoint; that is, whether they containno elements in common. The Collections class hasbinarySearch() method for searching a specifiedelement in a sorted List.TheAndroid-mania.com
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×