1 / 33

Collections Framework

Collections Framework. “A collections framework is a unified architecture for representing and manipulating collections.” Data Structures ---Interfaces & Implementations Algorithms ----through java.util.Collection s. First Data Structures…. “Collections”.

tblackwell
Download Presentation

Collections Framework

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Collections Framework • “A collections framework is a unified architecture for representing and manipulating collections.” • Data Structures ---Interfaces & Implementations • Algorithms ----through java.util.Collections

  2. First Data Structures….

  3. “Collections” • A collection groups multiple elements into a single unit. • Vector • Hashtable • array

  4. Hierarchy of Interfaces • Collection (java.util.Collection) • Set • SortedSet • List • Queue • Map • SortedMap

  5. Collection • “A collection represents a group of objects known as its elements.” • Some implementations allow duplicates, some don’t. • Some implementations automatically sort the elements, some don’t.

  6. Types of Collections • Set • Cannot contain duplicates. • SortedSet • Is a set. • Maintains elements in sorted order. • List • An ordered collection. • Queue • A collection with additional insertion, extraction, and inspection operations. • Usually FIFO.

  7. Collections that aren’t Collections • Map • Maps keys to values. • Cannot contain duplicate keys. • SortedMap • Maintains key/value pairs in key order.

  8. Set Implementations • HashSet • No order guarantee., like “hash table”. • TreeSet • Value ordered. • LinkedHashSet • Ordered oldest to newest, in terms of insertion. no duplicate elements are allowed in a Set

  9. List Implementations • ArrayList • Most common. • LinkedList • Use if insertions are often done at the head. Positional access: add elements at specific positions add and addAll without a position add to the end of the List set and remove return the element overwritten or removed Search: return the position of elements Extended Iteration: extended Iterator interface Range-view: return a sublist if the sublist is modified, the original List is as well

  10. Map Implementations • Hashtable • No order guarantee • Constant time get , put • no nulls • HashMap • Like Hashtable but allows nulls • TreeMap • Key order iteration. • LinkedHashMap • Insertion order iteration.

  11. Features of Maps • Copying via constructor: //m is another Map Map<K, V> copy = new HashMap<K, V>(m); • Check if 2 maps have same entries, if (m1.entrySet().containsAll(m2.entrySet())) { ... } • Check if two maps have the same keys: if (m1.keySet().equals(m2.keySet())) { ... }

  12. Queue Implementations • LinkedList • Allows for a FIFO queue. • PriorityQueue • Iteration based on a value specified at element insertion. • Has the property that only the highest-priority element can be accessed at any time.

  13. About Sorted Collection Classes • For o1.compareTo(o2): • returns negative if o1 < o2 • returns 0 if o1 == o2 • returns positive if o2 > o2 Sort by?

  14. SortedSet • Differences from Set: • Iterator traverses the SortedSet in order • toArray returns an in order array of the elements • toString returns a String of the contents in order Implementations: ConcurrentSkipListSet, TreeSet

  15. SortedMap • Differences from Map: • Iterator traverses the collection views of a SortedMap in order • toArray returns an in order array of the keys, values or entries • toString returns a String of the contents in order Implementations: ConcurrentSkipListMap, TreeMap

  16. Now a few common data structures….

  17. LinkedList Constant insertion and removal at first/last Constant insertion and removal at an Iterator Lookup is slow (linear time) Traversal is fast (constant time to find the next element) Ordered by insertion

  18. Trees Logarithmic insertion and lookup Sorted order Classes: TreeSet, TreeMap

  19. Review of some implementedcommon data structures

  20. Traversing through Collections….

  21. Iterate through Collections • for-each • If modification of the Collection won’t be done, use the for-each. for (Object o : collection){ System.out.println(o); } • Iterator • If modifications are to be done, or the for-each doesn’t excite you, use the Iterator.

  22. Iterator • “Enables you to traverse through a collection and to remove elements from the collection selectively, if desired.” • Use the iterator() method on the Collection to get the Collection’s Iterator. • Methods: • booleanhasNext() • Object next() • void remove() • Example Vector vec = new Vector;  // Populate it... Then later, iterate over its elements…..Iterator it = vec.iterator ();  while (it.hasNext ()) {    Object o = it.next (); //or whatever the class type is  }

  23. Another example – no casting ArrayList<String> alist = new ArrayList<String>(); // . . . Add Strings to alist ………not showing this //now cycle through and visit each element in ArrayList for (Iterator<String> it = alist.iterator(); it.hasNext(); ) { String s = it.next(); //no casting done here System.out.println(s); }

  24. Example again – with for ArrayList<String> alist = new ArrayList<String>(); // . . . Add Strings to alist ……… for (String s : alist) { System.out.println(s); }

  25. Example again –older style with casting ArrayList<String> alist = new ArrayList<String>(); // . . . Add Strings to alist ……… for (Iterator it = alist.iterator(); it.hasNext(); ) { String s = (String)it.next(); // Downcasting is required pre Java 5. System.out.println(s); }

  26. ListIterator Besides the basic Iterator class, ListIterator is implemented by the classes that implement the List interface (ArrayList, LinkedList, and Vector) Some methods: intnextIndex() Returns the index of the element that would be returned by a subsequent call to next(). intpreviousIndex() Returns the index of the element that would be returned by a subsequent call to previous().

  27. Converting Collection to Arrays Some Collections allow you to convert to an Array //c is a Collection of Objects Object[] a = c.toArray(); //c is a collection of Strings //we pass an empty string so the compiler knows the correct result type String[] a = c.toArray(new String[0]);

  28. Now for ALGORITHMS

  29. java.util.Collections --- HOW to get some predefined useful ALGORITHMS ---static method

  30. ALGORITHMSjava.util.Collections methods • The collections class has the following methods (static)..see API for complete list: • sort(List <?> list) - sort the list • binarySearch(List<? > list, T key) –binary search for key • reverse(List<?> list) - reverse the list • fill(List <? super T> list, E value) - overwrite every value in list with value • copy(List <? super T> src, List<? extends T> dest) - copy all the elements from src into dest • swap(List<?> list, inti, int j) - swap the elements at the ith and jth position in list • addAll(Collection<? super T> c, T... elements) - add all the specified elements to c:

  31. MORE ALGORITHMSjava.util.Collections methods • frequency(Collection<?> c, Object o) - how many times does o appear in c • disjoint(Collection<?> c1, Collection<?> c2) - returns true if c1 and c2 share no elements • min(Collection<? extends T> coll) – returns min (see API for overloaded min) • max(Collection<? extends T> coll) – returns max (see API for voverloaded max)

  32. Algorithms—example Sort import java.util.*; public class Sort { public static void main(String[] args) { List<String> list = Arrays.asList(args); //sort using the elements comparator Collections.sort(list); System.out.println(list); //sort using your own comparator Collections.sort(list, new MyComparator()); System.out.println(list); } }

  33. Algorithms- binarysearch example int pos = Collections.binarySearch(list, key); //if key isn’t in the list, add it in sorted order if (pos < 0) list.add(-pos-1), key); look up API to see why I add at -pos-1 position..hint if key is not found then binarySearch returns=(-(insertion point) - 1) Suppose pos= -4 that means insertion_point=3 So –pos -1 = -(-4) -1 = 4-1 =3

More Related