1 / 69

Java 2 Collection Classes

Java 2 Collection Classes. A Collection is a group of objects. A Map is a set of associations between objects.

latonial
Télécharger la présentation

Java 2 Collection Classes

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. Java 2 Collection Classes 95-712 Java Collections

  2. A Collection is a group of objects. A Map is a set of associations between objects. The core collection interfaces 95-712 Java Collections

  3. The Collection Interface • Root of a hierarchy • Some collections allow duplicates others do not • This interface allows you to pass collections around • Has generic methods such as contains() ,isEmpty(), • iterator() and size() 95-712 Java Collections

  4. The Set Interface Extends Collection • At most one null element • No duplicates, i.e., no elements such that e1.equals (e2) • If you try to add a duplicate then the add method • returns false 95-712 Java Collections

  5. The SortedSet Interface Extends Set • Guarantees that its iterator will traverse the set in ascending element order, sorted according to the natural ordering of its elements or by a comparator provided at sorted set creation. • If no comparator is specified then all elements of the set must implement the Comparable interface. • CompareTo or Compare is used. 95-712 Java Collections

  6. The List Interface Extends Collection • An ordered collection or sequence • Access by integer position • Access by search • Duplicates allowed • Like arrays--zero based • In some implementations, positional operations may execute in time proportional to the index value • Can return an Iterator (hasNext(), next(), remove()) or ListIterator(hasNext(), hasPrevious(), add(),…) • Add and remove can be done at end or at a particular index 95-712 Java Collections

  7. The Map Interface (Key, Value pairs) • Root of a hierarchy • No duplicate keys, duplicate values are okay • Three collection views • Set of keys via keySet() method • Collection of values via values() method • Set of key-value mappings via entrySet() • Methods include put(key,value) and get(key) 95-712 Java Collections

  8. The SortedMap Interface Extends Map A map that guarantees that it will be in ascending key order Sorted by natural ordering of its keys or by a comparator provided at SortedMap creation time Ordering must be consistent with equals. It uses the compare or compareTo methods 95-712 Java Collections

  9. Abstract Classes • General Notes: • Can’t be instantiated • A subclass of an abstract class can be instantiated if it • overrides each abstract method in the superclass and • provides a body for each. 95-712 Java Collections

  10. Abstract Classes AbstractCollection Partial implementation of the Collection interface Makes it easy to define custom Collection implementations AbstractSet, AbstractList and so on… Partial implementation of these interfaces If you want to create your own custom built Collections, start by extending the appropriate abstract class. In what follows we will be using existing (built-in) classes. 95-712 Java Collections

  11. Concrete Classes 95-712 Java Collections

  12. Class HashSet Extends AbstractSet • Implements set interface • Backed by a hash table (HashMap instance) • No guarantees as to iteration order • O(1) for add, remove, contains, size -- if the hash • function is good • Iteration depends on O(N + tablesize) 95-712 Java Collections

  13. // Demonstration of HashSet UseHashSet.java import java.util.*; public class UseHashSet { public static void main(String args[]) { // create a set object -- this is a HashSet implementation Set set = new HashSet(); 95-712 Java Collections

  14. // Add some values to the set set.add("Moe"); set.add("Curly"); set.add("Larry"); set.add("Larry"); set.add("Curly Joe"); // does the set contain "Larry" if(set.contains("Larry")) System.out.println("Larry in set"); // how many elements are in the set System.out.println("The set contains " + set.size() + " elements"); 95-712 Java Collections

  15. // remove "Curly" set.remove("Curly"); System.out.println("The set contains " + set.size() + " elements"); // iterate over the contents of the set and display the values // first, create an iterator object based on this set Iterator myIter = set.iterator(); // use two of the three iterator methods -- hasNext(), next(), remove() while(myIter.hasNext()) { String name = (String) myIter.next(); System.out.println(name); } } } 95-712 Java Collections

  16. // Output Larry in set The set contains 4 elements The set contains 3 elements Curly Joe Larry Moe 95-712 Java Collections

  17. // Storing objects other than Strings // UseHashSet2.java // override Object's hashCode() and equals() import java.util.*; class IntVariable { private String uniqueIdentifier; private int value; public IntVariable(String name, int value) { uniqueIdentifier = name; this.value = value; } 95-712 Java Collections

  18. public int getValue() { return value; } public String toString() { return "[" + uniqueIdentifier + "] = " + value; } public int hashCode() { return uniqueIdentifier.hashCode(); } 95-712 Java Collections

  19. public boolean equals(Object other) { if(other != null && getClass() == other.getClass()) { IntVariable otherVar = (IntVariable) other; return(uniqueIdentifier.equals(otherVar.uniqueIdentifier)); } else return false; } } 95-712 Java Collections

  20. public class UseHashSet2 { public static void main(String args[]) { Set symbolTable = new HashSet(); IntVariable x = new IntVariable("X",23), y = new IntVariable("Y",45); symbolTable.add(x); symbolTable.add(y); Iterator iter = symbolTable.iterator(); while(iter.hasNext()) { System.out.println(iter.next()); } } } 95-712 Java Collections

  21. //Output [Y] = 45 [X] = 23 95-712 Java Collections

  22. // Demonstrate HashSets FindDups.java // Note how the output is not ordered import java.util.*; public class FindDups{ public static void main(String args[]) { Set s = new HashSet(); for(int i = 0; i < args.length; i++) { if(!s.add(args[i])) System.out.println("Duplicate detected: " + args[i]); } System.out.println(s.size() + " distinct words detected: " + s); } } 95-712 Java Collections

  23. //Output java FindDups It depends what the meaning of is is . Duplicate detected: is 8 distinct words detected: [what, depends, the, It, ., is, meaning, of] 95-712 Java Collections

  24. Class TreeSet Extends AbstractSet • Implements set • Backed by Treemap • Ascending element order (natural order or • comparator) • O(Log(n)) for the methods add, remove, and contains 95-712 Java Collections

  25. // Demonstrate a TreeSet UseTreeSet.java import java.util.*; public class UseTreeSet { public static void main(String args[]) { // create a set object -- // This is a Red Black tree implementation Set set = new TreeSet(); 95-712 Java Collections

  26. // Add some values to the set set.add("Moe"); set.add("Curly"); set.add("Larry"); set.add("Larry"); set.add("Curly Joe"); // does the set contain "Larry" if(set.contains("Larry")) System.out.println("Larry in set"); // how many elements are in the set System.out.println("The set contains " + set.size() + " elements"); 95-712 Java Collections

  27. // remove "Curly" set.remove("Curly"); System.out.println("The set contains " + set.size() + " elements"); // iterate over the contents of the set and display the values // first, create an iterator object based on this set Iterator myIter = set.iterator(); // use two of the three iterator methods -- hasNext(), next(), remove() while(myIter.hasNext()) { String name = (String) myIter.next(); System.out.println(name); } } } 95-712 Java Collections

  28. /* Larry in set The set contains 4 elements The set contains 3 elements Curly Joe Larry Moe */ 95-712 Java Collections

  29. // Adding objects to a set UseTreeSet2.java // storing objects other than Strings // implement Comparable import java.util.*; class IntVariable implements Comparable { private String uniqueIdentifier; private int value; public IntVariable(String name, int value) { uniqueIdentifier = name; this.value = value; } 95-712 Java Collections

  30. public int getValue() { return value; } public String toString() { return "[" + uniqueIdentifier + "] = " + value; } public int compareTo(Object other) { if(other != null && getClass() == other.getClass()) { IntVariable otherVar = (IntVariable) other; return(uniqueIdentifier.compareTo(otherVar.uniqueIdentifier)); } else throw new ClassCastException("Illegal IntVariable Compare"); } } 95-712 Java Collections

  31. public class UseTreeSet2 { public static void main(String args[]) { Set symbolTable = new TreeSet(); IntVariable x = new IntVariable("X",23), y = new IntVariable("Y",45); symbolTable.add(x); symbolTable.add(y); Iterator iter = symbolTable.iterator(); while(iter.hasNext()) { System.out.println(iter.next()); } } } 95-712 Java Collections

  32. /* [X] = 23 [Y] = 45 */ 95-712 Java Collections

  33. // Demonstration of TreeSet FindDups2.java // Note how the output is ordered import java.util.*; public class FindDups2{ public static void main(String args[]) { Set s = new TreeSet(); for(int i = 0; i < args.length; i++) { if(!s.add(args[i])) System.out.println("Duplicate detected: " + args[i]); } 95-712 Java Collections

  34. System.out.println(s.size() + " distinct words detected: " + s); } } /* java FindDups2 It depends what the meaning of is is . Duplicate detected: is 8 distinct words detected: [., It, depends, is, meaning, of, the, what] */ 95-712 Java Collections

  35. Class LinkedList Extends AbstractsSequentialList Implements List • get, remove, insert at the beginning and end of the list • Allow linked lists to be used as a stack, queue, or double- • ended queue (deque) • Doubly linked list is used 95-712 Java Collections

  36. // Queue Demonstration UseQueue.java import java.util.*; public class UseQueue { public static void main(String args[]) { // create a linked list LinkedList queue = new LinkedList(); 95-712 Java Collections

  37. // add a few characters to the end of the queue queue.addLast(new Character('B')); queue.addLast(new Character('A')); queue.addLast(new Character('C')); // remove all the elements from the front and display while(!queue.isEmpty()) { Character c = (Character) queue.removeFirst(); char c2 = c.charValue(); System.out.println(c2); } } } 95-712 Java Collections

  38. java UseQueue B A C 95-712 Java Collections

  39. // Demonstrate Stacks in Java UseStack.java import java.util.*; public class UseStack { public static void main(String args[]) { // create a linked list LinkedList stack = new LinkedList(); 95-712 Java Collections

  40. // push a few characters on the top of the stack stack.addFirst(new Character('B')); stack.addFirst(new Character('A')); stack.addFirst(new Character('C')); // pop all the elements and display them while(!stack.isEmpty()) { Character c = (Character) stack.removeFirst(); char c2 = c.charValue(); System.out.println(c2); } } } 95-712 Java Collections

  41. /* C A B */ 95-712 Java Collections

  42. Class ArrayList Extends AbstractList Implements List • Implemented by a resizable array • O(1) for size, isempty, get, set, iterator, listiterator • Add runs in amortized constant time, adding n • elements requires O(n) time • Capacity grows automatically • Details of add and growth are not specified 95-712 Java Collections

  43. Class HashMap Extends AbstractMap Implements Map Hash table based implementation of map No guarantees as to the order of the map O(1) for operations like get and put if hash function is good O(n + tablesize) for iteration 95-712 Java Collections

  44. // Demonstration of HashMap Freq.java import java.util.*; public class Freq { private static final Integer ONE = new Integer(1); public static void main(String args[]) { Map m = new HashMap(); for(int i = 0; i < args.length; i++) { Integer freq = (Integer) m.get(args[i]); m.put(args[i], (freq == null ? ONE : new Integer(freq.intValue() + 1))); } 95-712 Java Collections

  45. System.out.println(m.size() + " distinct words detected:"); System.out.println(m); } } /* java Freq that's a hard way to go go 6 distinct words detected: {a=1, hard=1, go=2, to=1, way=1, that's=1} */ 95-712 Java Collections

  46. // HashMap demonstration UseHashMap.java import java.util.*; public class UseHashMap { public static void main(String args[]) { // create a hash table Map table = new HashMap(); // add a few id's and names to the table table.put("123456543", "Moe"); table.put("123456789", "Curly"); table.put("165987651", "Larry"); 95-712 Java Collections

  47. // query the table String name = (String)table.get("123456543"); if(name != null) System.out.println(name); name = (String)table.get("111223333"); if(name != null) System.out.println(name); else System.out.println("Not in table"); // replace an element table.put("123456789", "Curly Joe"); // see if it's there name = (String)table.get("123456789"); if(name != null) System.out.println(name); 95-712 Java Collections

  48. // remove an element table.remove("165987651"); // display the whole table by calling its toString() method System.out.println(table); } } /* java UseHashMap Moe Not in table Curly Joe {123456789=Curly Joe, 123456543=Moe} */ 95-712 Java Collections

  49. // HashMap demonstration SymbolTable.java // storing objects other than Strings import java.util.*; class IntVariable { private String uniqueIdentifier; private int value; public IntVariable(String name, int value) { uniqueIdentifier = name; this.value = value; } 95-712 Java Collections

  50. public int hashCode() { return uniqueIdentifier.hashCode(); } public boolean equals(Object other) { if(other != null && getClass() == other.getClass()) { IntVariable otherVar = (IntVariable) other; return(uniqueIdentifier.equals(otherVar.uniqueIdentifier)); } else return false; } public int getValue() { return value; } public String getID() { return uniqueIdentifier; } public String toString() { return "["+uniqueIdentifier+value+"]"; } } 95-712 Java Collections

More Related