Presentation is loading. Please wait.

Presentation is loading. Please wait.

Geoff Holmes Palindrome solutions Overview Arrays Collections Enumerators Vector BitSet Stack Dictionary Hashtable Collection Classes (Chapter 19) import.

Similar presentations


Presentation on theme: "Geoff Holmes Palindrome solutions Overview Arrays Collections Enumerators Vector BitSet Stack Dictionary Hashtable Collection Classes (Chapter 19) import."— Presentation transcript:

1 Geoff Holmes Palindrome solutions Overview Arrays Collections Enumerators Vector BitSet Stack Dictionary Hashtable Collection Classes (Chapter 19) import java.util.*;

2 Department of Computer Science2 Palindrome1 solution public class palindrome1 { public static void main (String [] args) { StringBuffer s = new StringBuffer (args[0]); StringBuffer t = new StringBuffer (args[0]); if (s.toString().equals(t.reverse().toString())) System.out.println(s+" is a palindrome"); else System.out.println(s+" is not a palindrome"); }

3 Department of Computer Science3 Palindrome 2 solution public class palindrome { public static void main (String [] args) { String s = args[0]; for (int i=0; i<s.length()/2; i++) { if (!(s.charAt(i) == (s.charAt(s.length()-1-i)))) { System.out.println(s+" is not a palindrome"); return; } System.out.println(s+" is a palindrome"); }

4 Department of Computer Science4 Overview Collection classes draw together the work we did last lecture on Object(s) and Enumerators by providing frameworks for storing collections of objects and working our way through them. Wrapper classes are important because collections only deal with objects!

5 Department of Computer Science5 Arrays – primitive types and size public class array1 { public static void main (String args []) { int [ ] x = {0, 1, 2}; System.out.println(x[3]); } Can Initialize easily using { } This code produces ArrayIndexOutOfBoundsException Have a uniform type (primitives or classes), but is polymorphic: e.g. Object[ ] can hold instances of any class

6 Department of Computer Science6 Arrays – size not known Need to use new to create array size dynamically (at runtime) public class array2 { public static void main (String args []) { int [ ] x; Integer a = new Integer(args[0]); x = new int [a.intValue()]; for (int i=0; i<a.intValue(); i++) x[i] = i; for (int i=0; i<a.intValue(); i++) System.out.println(x[i]); }

7 Department of Computer Science7 Arrays – non-primitive types Elements and Array MUST use new public class array3 { public static void main (String args []) { Integer a = new Integer(args[0]); Integer [ ] x = new Integer [a.intValue()]; // have an array of handles at this point for (int i=0; i<a.intValue(); i++) x[i] = new Integer(i); for (int i=0; i<a.intValue(); i++) System.out.println(x[i].intValue()); }

8 Department of Computer Science8 Arrays of Object public class array4 { public static void main (String args []) { Object [ ] x = new Object [3]; x[0] = new Integer(12); x[1] = new Float (3.14159); x[2] = new String ("Fred"); }

9 Department of Computer Science9 Arrays of “real” objects class fred {} public class array2 { public static void main (String args []) { fred [ ] x; // x has no handle! fred [ ] y = new fred [3]; // y has 3 handles set to null fred [ ] z = new fred [3]; for (int i=0; i<z.length; i++) z[i] = new fred(); fred [ ] a = { new fred(), new fred(), new fred() }; //System.out.println("x length = " + x.length); compiler error System.out.println("y length = " + y.length); System.out.println("z length = " + z.length); System.out.println("a length = " + a.length); }

10 Department of Computer Science10 Collections (Vector, BitSet, Stack and Hashtable) Use arrays for objects and only option for primitives – incr sophistication using a collection class Maintain their values as type Object   Cannot store primitives directly, must use wrapper classes (Integer, Boolean, …)  Must cast back retrieved objects to their original type Can be seen as a linear sequence of elements: support Enumeration interface

11 Department of Computer Science11 Enumerators Uniform way of iterating through the elements of whatever type collection: boolean hasMoreElements() Object nextElement() Always invoke these two in tandem,  Never call nextElement() without first checking hasMoreElements() for truth  Never call nextElement() twice in a row Typical code patterns are: for(Enumeration e = htab.elements(); e.hasMoreElements(); ) System.out.println(e.nextElement);  Or: Enumeration e = htab.elements(); while (e.hasMoreElements()) System.out.println(e.nextElement);

12 Department of Computer Science12 Vector Similar to arrays, but more general operations supported:  (automatically) expandable! Size: size(), isEmpty(), capacity(), setSize(int) Access: contains(Object), firstElement(), lastElement(), elementAt(int) Insert/modify: addElement(Object), setElementAt(Object,int),insertElement(Object,int) Remove: removeElementAt(int),removeElement(Object), removeAllElements() Search: indexOf(Object), lastIndexOf(Object) Misc: clone(), toString()

13 Department of Computer Science13 Vector is very flexible Array: v.setElementAt(v.elementAt(37)+12,5); Stack: addElement(), lastElement(), removeElementAt(v.size( )-1) Queue: add to back, remove from front: addElement(), firstElement(), removeElementAt(0) Set: contains(), addElement(), removeElement() List: Insert and remove at any location insertElementAt(Object,int) removeElementAt(Object,int)

14 Department of Computer Science14 Apples and Oranges Java protects against mixing objects of different types in a vector but only at runtime – this is because we can addElement any Object but must CAST the object back when retrieving (using elementAt) See applesandoranges.java See applesandoranges2.java for enumerator version.

15 Department of Computer Science15 BitSet – Vector of bits! Expandable like Vector, alternative to boolean[], supports more methods (see Sieve example): BitSet(int) constructor, all bits are off (0) initially void set(int) set a bit boolean get(int) get bit status void clear(int) clear a bit (set to 0) void or(BitSet) compute logical-or of two bitsets void and(BitSet) void xor(BitSet) String toString(): nice list of comma-separated on-positions

16 Department of Computer Science16 Stack – LIFO (pile of papers) Subclass of Vector: Object push(Object) Object peek() Object pop() int size() boolean empty() int search(Object): -1 if not found, 1 for top of stack, … (book is wrong) (cf. chapter 10 for pro/cons “Stack extends Vector”)

17 Department of Computer Science17 Abstract class Dictionary Relate arbitrary values to keys: Object get(Object key) Object put(Object key, Object value) Object remove(Object key) Hashtable: subclass, adds useful methods boolean containsKey(Object key) boolean containsValue(Object value) Enumeration elements() Enumeration keys() void clear() ( see Concordance code example)

18 Department of Computer Science18 Hashtable A Vector associates numbers with objects If you want to pick objects on another basis then use a Stack – pick the last thing pushed on by popping off. What about looking up objects based on another object? This is what a Dictionary provides (size(), isEmpty(), put, get and remove)

19 Department of Computer Science19 Concordance – hash array of sets private void enterWord(String word, Integer line) { Vector set = (Vector) dict.get(word); if (set == null) { set = new Vector(); dict.put(word,set); } if (! set.contains(line)) set.addElement(line); }

20 Department of Computer Science20 Output public void generateOutput(PrintStream output) { Enumeration e = dict.keys(); while (e.hasMoreElements()) { String word = (String) e.nextElement(); Vector set = (Vector) dict.get(word); output.print(word + ": "); Enumeration f = set.elements(); while (f.hasMoreElements()) output.print(f.nextElement() + " "); output.println(""); }


Download ppt "Geoff Holmes Palindrome solutions Overview Arrays Collections Enumerators Vector BitSet Stack Dictionary Hashtable Collection Classes (Chapter 19) import."

Similar presentations


Ads by Google