Download presentation
Presentation is loading. Please wait.
Published byIsaac Vincent Jones Modified over 8 years ago
1
Collections –data structures and Algorithms L. Grewe
2
Collections Framework “A collections framework is a unified architecture for representing and manipulating collections.” “A collections framework is a unified architecture for representing and manipulating collections.” Data Structures ---Interfaces & ImplementationsData Structures ---Interfaces & Implementations Algorithms ----through java.util.CollectionsAlgorithms ----through java.util.Collections
3
First Data Structures….
4
“Collections” A collection groups multiple elements into a single unit. A collection groups multiple elements into a single unit. VectorVector HashtableHashtable arrayarray
5
Hierarchy of Interfaces Collection (java.util.Collection) Collection (java.util.Collection) SetSet SortedSet SortedSet ListList QueueQueue Map Map SortedMapSortedMap
6
Collection “A collection represents a group of objects known as its elements.” “A collection represents a group of objects known as its elements.” Some implementations allow duplicates, some don’t. Some implementations allow duplicates, some don’t. Some implementations automatically sort the elements, some don’t. Some implementations automatically sort the elements, some don’t.
7
Types of Collections Set Set Cannot contain duplicates.Cannot contain duplicates. SortedSet SortedSet Is a set.Is a set. Maintains elements in sorted order.Maintains elements in sorted order. List List An ordered collection.An ordered collection. Queue Queue A collection with additional insertion, extraction, and inspection operations.A collection with additional insertion, extraction, and inspection operations. Usually FIFO.Usually FIFO.
8
Collections that aren’t Collections Map Map Maps keys to values.Maps keys to values. Cannot contain duplicate keys.Cannot contain duplicate keys. SortedMap SortedMap Maintains key/value pairs in key order.Maintains key/value pairs in key order.
9
Set Implementations HashSet HashSet No order guarantee., like “hash table”.No order guarantee., like “hash table”. TreeSet TreeSet Value ordered.Value ordered. LinkedHashSet LinkedHashSet Ordered oldest to newest, in terms of insertion.Ordered oldest to newest, in terms of insertion. no duplicate elements are allowed in a Set
10
List Implementations ArrayList ArrayList Most common.Most common. LinkedList LinkedList Use if insertions are often done at the head.Use if insertions are often done at the head. Positional access: add elements at specific positions add elements at specific positions add and addAll without a position add to the end of the List add and addAll without a position add to the end of the List set and remove return the element overwritten or removed set and remove return the element overwritten or removed Search: return the position of elements Search: return the position of elements Extended Iteration: extended Iterator interface Extended Iteration: extended Iterator interface Range-view: Range-view: return a sublist return a sublist if the sublist is modified, the original List is as well if the sublist is modified, the original List is as well
11
Map Implementations Hashtable Hashtable No order guaranteeNo order guarantee Constant time get, putConstant time get, put no nullsno nulls HashMap HashMap Like Hashtable but allows nullsLike Hashtable but allows nulls TreeMap TreeMap Key order iteration.Key order iteration. LinkedHashMap LinkedHashMap Insertion order iteration.Insertion order iteration.
12
Features of Maps Copying via constructor: Copying via constructor: //m is another Map Map copy = new HashMap (m); Check if 2 maps have same entries, Check if 2 maps have same entries, if (m1.entrySet().containsAll(m2.entrySet())) {...} Check if two maps have the same keys: Check if two maps have the same keys: if (m1.keySet().equals(m2.keySet())) {...}
13
Queue Implementations LinkedList LinkedList Allows for a FIFO queue.Allows for a FIFO queue. PriorityQueue PriorityQueue Iteration based on a value specified at element insertion.Iteration based on a value specified at element insertion. Has the property that only the highest- priority element can be accessed at any time.Has the property that only the highest- priority element can be accessed at any time.
14
About Sorted Collection Classes Sort by? ObjectNatural Ordering Byte, Integer, Long, Short, Float, Double, BigInteger, BigDecimalSigned Numerical CharacterUnsigned Numerical BooleanBoolean.FALSE < Boolean.TRUE File System Dependent Alphabetical by Path StringAlphabetical DateChronological CollationKeyLocale-Specific Alphabetical For o1.compareTo(o2) : returns negative if o1 < o2 returns 0 if o1 == o2 returns positive if o2 > o2
15
SortedSet Differences from Set: Differences from Set: Iterator traverses the SortedSet in order Iterator traverses the SortedSet in order toArray returns an in order array of the elements toArray returns an in order array of the elements toString returns a String of the contents in order toString returns a String of the contents in order Implementations: ConcurrentSkipListSet, TreeSet ConcurrentSkipListSet TreeSetConcurrentSkipListSet TreeSet
16
SortedMap Differences from Map: Differences from Map: Iterator traverses the collection views of a SortedMap in order Iterator traverses the collection views of a SortedMap in order toArray returns an in order array of the keys, values or entries toArray returns an in order array of the keys, values or entries toString returns a String of the contents in order toString returns a String of the contents in order Implementations: ConcurrentSkipListMap, TreeMap ConcurrentSkipListMap TreeMapConcurrentSkipListMap TreeMap
17
Now a few common data structures….
18
LinkedList Constant insertion and removal at first/last Constant insertion and removal at first/last Constant insertion and removal at an Iterator Constant insertion and removal at an Iterator Lookup is slow (linear time) Lookup is slow (linear time) Traversal is fast (constant time to find the next element) Traversal is fast (constant time to find the next element) Ordered by insertion Ordered by insertion
19
Trees Logarithmic insertion and lookup Logarithmic insertion and lookup Sorted order Sorted order Classes: TreeSet, TreeMap Classes: TreeSet, TreeMap
20
Review of some implemented common data structures InterfacesImplementations Hash Table Resizable Array TreeLinked List Hash Table + Linked List SetHashSetTreeSet LinkedHash Set ListArrayListLinkedList Queue MapHashMapTreeMap LinkedHash Map
21
Traversing through Collections….
22
Iterate through Collections for-each for-each If modification of the Collection won’t be done, use the for-each.If modification of the Collection won’t be done, use the for-each. for (Object o : collection){ System.out.println(o);} Iterator Iterator If modifications are to be done, or the for- each doesn’t excite you, use the Iterator.If modifications are to be done, or the for- each doesn’t excite you, use the Iterator.
23
Iterator “Enables you to traverse through a collection and to remove elements from the collection selectively, if desired.” “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. Use the iterator() method on the Collection to get the Collection’s Iterator. Methods: Methods: boolean hasNext()boolean hasNext() Object next()Object next() void remove()void remove() Example 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 } 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 }
24
Another example – no casting ArrayList alist = new ArrayList (); //... Add Strings to alist ………not showing this //... Add Strings to alist ………not showing this //now cycle through and visit each element in ArrayList for (Iterator it = alist.iterator(); it.hasNext(); ) { String s = it.next(); //no casting done here System.out.println(s); } System.out.println(s); }
25
Example again – with for ArrayList alist = new ArrayList (); //... Add Strings to alist ……… //... Add Strings to alist ……… for (String s : alist) { System.out.println(s); } { System.out.println(s); }
26
Example again –older style with casting ArrayList alist = new ArrayList (); //... Add Strings to alist ……… //... Add Strings to alist ……… for (Iterator it = alist.iterator(); it.hasNext(); ) { String s = (String)it.next(); // Downcasting is required pre Java 5. { String s = (String)it.next(); // Downcasting is required pre Java 5. System.out.println(s); } System.out.println(s); }
27
ListIterator Besides the basic Iterator class, ListIterator is implemented by the classes that implement the List interface (ArrayList, LinkedList, and Vector) Besides the basic Iterator class, ListIterator is implemented by the classes that implement the List interface (ArrayList, LinkedList, and Vector) Some methods: Some methods: int nextIndex() Returns the index of the element that would be returned by a subsequent call to next(). int nextIndex() Returns the index of the element that would be returned by a subsequent call to next().nextIndexnext()nextIndexnext() int previousIndex() Returns the index of the element that would be returned by a subsequent call to previous(). int previousIndex() Returns the index of the element that would be returned by a subsequent call to previous().previousIndexprevious()previousIndexprevious()
28
Converting Collection to Arrays Some Collections allow you to convert to an Array 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]);
29
Now for ALGORITHMS
30
java.util.Collections --- HOW to get some predefined useful ALGORITHMS ---static method HOW to get some predefined useful ALGORITHMS ---static method
31
ALGORITHMS java.util.Collections methods The collections class has the following methods (static)..see API for complete list: The collections class has the following methods (static)..see API for complete list: sort(List list) - sort the listsort(List list) - sort the list binarySearch(List list, T key) –binary search for keybinarySearch(List list, T key) –binary search for key reverse(List list) - reverse the listreverse(List list) - reverse the list fill(List list, E value) - overwrite every value in list with valuefill(List list, E value) - overwrite every value in list with value copy(List src, List dest) - copy all the elements from src into destcopy(List src, List dest) - copy all the elements from src into dest swap(List list, int i, int j) - swap the elements at the ith and jth position in listswap(List list, int i, int j) - swap the elements at the ith and jth position in list addAll(Collection c, T... elements) - add all the specified elements to c:addAll(Collection c, T... elements) - add all the specified elements to c:
32
MORE ALGORITHMS java.util.Collections methods frequency(Collection c, Object o) - how many times does o appear in cfrequency(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 elementsdisjoint(Collection c1, Collection c2) - returns true if c1 and c2 share no elements min(Collection coll) – returns min (see API for overloaded min)min(Collection coll) – returns min (see API for overloaded min) max(Collection coll) – returns max (see API for voverloaded max)max(Collection coll) – returns max (see API for voverloaded max)
33
Algorithms—example Sort import java.util.*; public class Sort { public static void main(String[] args) { public static void main(String[] args) { List list = Arrays.asList(args); List list = Arrays.asList(args); //sort using the elements comparator //sort using the elements comparator Collections.sort(list); Collections.sort(list); System.out.println(list); System.out.println(list); //sort using your own comparator //sort using your own comparator Collections.sort(list, new MyComparator()); Collections.sort(list, new MyComparator()); System.out.println(list); System.out.println(list); }}
34
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 Suppose pos= -4 that means insertion_point=3 So –pos -1 = -(-4) -1 = 4-1 =3 So –pos -1 = -(-4) -1 = 4-1 =3
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.