De presentatie wordt gedownload. Even geduld aub

De presentatie wordt gedownload. Even geduld aub

H 22. COLLECTIONS FRAMEWORK. 1. INLEIDING.

Verwante presentaties


Presentatie over: "H 22. COLLECTIONS FRAMEWORK. 1. INLEIDING."— Transcript van de presentatie:

1 H 22. COLLECTIONS FRAMEWORK. 1. INLEIDING.
Meest voorkomende datastructuren gestandaardiseerd en efficient geïmplementeerd. Goed voorbeeld van herbruikbare code JAVA

2 2. OVERZICHT COLLECTIONS FRAMEWORK
Data structuur (object) die referenties naar andere objecten bijhoudt. Collections framework Interfaces die de operaties declareren voor verschillende collection types en verschillende implementaties (classes) daarvan. Behoren tot het package java.util Set List Map JAVA

3 Voorziet static methoden voor manipulatie van arrays
3. CLASS ARRAYS Class Arrays Voorziet static methoden voor manipulatie van arrays Voorziet “high-level” methoden Methode binarySearch voor het zoeken in geordende arrays Methode equals voor het vergelijken Method fill voor waarden in te brengen Method sort voor sorteren JAVA

4 3. CLASS ARRAYS : Voorbeeld methoden.
import java.util.*; public class UsingArrays { private int intValues[] = { 1, 2, 3, 4, 5, 6 }; private double doubleValues[] = { 8.4, 9.3, 0.2, 7.9, 3.4 }; private int filledInt[], intValuesCopy[]; public UsingArrays() // initialize arrays filledInt = new int[ 10 ]; intValuesCopy = new int[ intValues.length ]; // vul filledInt volledig op met 7’s Arrays.fill( filledInt, 7 ); // sorteer doubleValues in oplopende volgorde Arrays.sort( doubleValues ); // copy array intValues naar array intValuesCopy System.arraycopy( intValues, 0, intValuesCopy, 0, intValues.length ); } JAVA

5 3. Methode arraycopy // copy array intValues naar array intValuesCopy
System.arraycopy( intValues, 0, intValuesCopy, 0, intValues.length ); static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) Parameters: src - de source array. srcPos - start positie in de source array. dest - de destination array. destPos - start positie in de destination array. length – aantal elementen die gekopieerd moeten worden. Werpt: IndexOutOfBoundsException – indien de grenzen van src of dest overschreden worden. ArrayStoreException – indien het type van de array src niet in dest geplaatst kan worden. NullPointerException – indien src of dest null is. JAVA

6 3. CLASS ARRAYS : Voorbeeld methoden.
public void doiets() { //vergelijk de inhoud van beide arrays boolean b = Arrays.equals( intValues, intValuesCopy ); //... // element opzoeken int location= Arrays.binarySearch( intValues, value ); //indien value = 5 returns 4 //indien value = 8763 returns –7 // -7 = de indexwaarde_in_geval_van_invoegen*-1 -1 } JAVA

7 3. CLASS ARRAYS : overloaded methoden
static int binarySearch(int[] a, int key) static int binarySearch(double[] a, double key) Idem voor char, byte, short, long en float static int binarySearch(Object[] a, Object key) static int binarySearch(Object[] a, Object key, Comparator c)  zie paragraaf 6. static boolean equals(int[] a, int[] a2) Idem voor char, byte, short, long, float en double static boolean equals(Object[] a, Object[] a2) JAVA

8 3. CLASS ARRAYS : overloaded methoden
static void fill(int[] a, int val) static void fill(int[] a, int fromIndex, int toIndex, int val) IllegalArgumentException – if fromIndex > toIndex ArrayIndexOutOfBoundsException – if fromIndex < 0 of toIndex > a.length Idem voor char, byte, short, long, float, double en object JAVA

9 3. CLASS ARRAYS : overloaded methoden
static void sort(int[] a) static void sort(int[] a, int fromIndex, int toIndex) IllegalArgumentException – if fromIndex > toIndex ArrayIndexOutOfBoundsException – if fromIndex < 0 of toIndex > a.length Idem voor char, byte, short, long, float en double static void sort(Object[] a) static void sort(Object[] a, Comparator c) static void sort(Object[] a, int fromIndex, int toIndex) static void sort(Object[] a, int fromIndex, int toIndex, Comparator c)  zie paragraaf 6. JAVA

10 3. CLASS ARRAYS : static methode asList
static methode asList laat toe een Arrays object als een List (zie verder) te doorlopen. Wijzigen op de elementen via de List view zijn effectief in het Arrays object, en vise versa. Opm: de List is wel van vaste lengte (geen add of remove!). Voorbeeld: import java.util.*; public class UsingAsList { private static final String values[] = { "red", "white", "blue" }; private List list; // initialiseer List en wijzig (set methode) de waarde // op locatie 1 public UsingAsList() { list = Arrays.asList( values ); // get List list.set( 1, "green" ); // wijzig een waarde } JAVA

11 3. CLASS ARRAYS : static methode asList
// output via List en via array public void printElements() { System.out.print( "List elements : " ); for ( int count = 0; count < list.size(); count++ ) System.out.print( list.get( count ) + " " ); System.out.print( "\nArray elements: " ); for ( int count = 0; count < values.length; count++ ) System.out.print( values[ count ] + " " ); System.out.println(); } public static void main( String args[] ) new UsingAsList().printElements(); List elements : red green blue Array elements: red green blue JAVA

12 4. INTERFACE COLLECTION EN CLASS COLLECTIONS.
Bevat bulk operations (op de volledige container) Adding, clearing, comparing en retaining objects Interfaces Set en List extend interface Collection Voorziet een Iterator (zoals Enumeration) die ook elementen kan verwijderen. Class Collections Voorziet static methoden die collections manipuleren Polymorfisme wordt hierbij ondersteund JAVA

13 Interface Collection Interface List
5. LIST INTERFACE. Interface Collection Interface List Vector, ArrayList en LinkedList zijn implementatie klassen van interface List. JAVA

14 Oefening: bulk operaties.
Collection interface: boolean add(Object o); boolean addAll(Collection c); void clear(); boolean contains(Object o); boolean containsAll(Collection o); boolean equals(Object o); int hashCode(); boolean isEmpty(); Iterator iterator(); boolean remove(Object o); boolean removeAll(Collection c); boolean retainAll(Collection c); int size(); Object[] toArray(); Object[] toArray(Object [] a); String arX[] = {"appel", "peer", "citroen", "kiwi"}, arY[] = {"banaan", "mango", "citroen", "kiwi", "zespri"} Behandel arX en arY als Collections en maak gebruik van de bulk operaties om volgende output te leveren: In y zit extra [banaan, mango, zespri] In x zit extra [appel, peer] x en y hebben gemeenschappelijk [citroen, kiwi] JAVA

15 Oefening: bulk operaties.
String arX[] = {"appel", "peer", "citroen", "kiwi"}, arY[] = {"banaan", "mango", "citroen", "kiwi", "zespri"} In y zit extra [banaan, mango, zespri] In x zit extra [appel, peer] x en y hebben gemeenschappelijk [citroen, kiwi] vector2 = new Vector(collection) Interface Collection: boolean removeAll(Collection c)           Removes all this collection's elements that are also contained in the specified collection.  boolean retainAll(Collection c)           Retains only the elements in this collection that are contained in the specified collection (optional operation). JAVA

16 5. LIST INTERFACE. List Geordende Collection waarbij duplicaten toegelaten zijn: SEQUENCE. List index start ook van nul. Implementatie klassen: ArrayList (resizable-array implementatie) LinkedList (linked-list implementatie) Vector (zoals ArrayList maar synchronized) JAVA

17 5. Voorbeeld : ARRAYLIST import java.awt.Color; import java.util.*;
public class CollectionTest { private static final String colors[]={ "red","white","blue"}; public CollectionTest() List list = new ArrayList(); // opvullen van de Arraylist list.add( Color.MAGENTA ); // toevoegen van color object for ( int count = 0; count < colors.length; count++ ) list.add( colors[ count ] ); // van string objecten list.add( Color.CYAN ); // van color object JAVA

18 5. Voorbeeld : ARRAYLIST // afdrukken
System.out.println( "\nArrayList: " ); for ( int count = 0; count < list.size(); count++ ) System.out.print( list.get( count ) + " " ); // verwijder alle String objecten removeStrings( list ); System.out.println( //opnieuw afdrukken "\n\nArrayList after calling removeStrings: " ); } JAVA

19 5. Voorbeeld : ARRAYLIST private void removeStrings( Collection collection ) { Iterator iterator = collection.iterator(); // get iterator while ( iterator.hasNext() ) if ( iterator.next() instanceof String ) iterator.remove(); // remove String object } public static void main( String args[] ) { new CollectionTest(); ArrayList: java.awt.Color[r=255,g=0,b=255] red white blue java.awt.Color [r=0,g=255,b=255] ArrayList after calling removeStrings: java.awt.Color[r=255,g=0,b=255] java.awt.Color[r=0,g=255,b=255] JAVA

20 5. Voorbeeld : LINKEDLIST 1
import java.util.*; public class ListTest { private static final String colors[] = { "black", "yellow", "green", "blue", "violet", "silver" }; private static final String colors2[] = { "gold", "white", "brown", "blue", "gray", "silver" }; // aanmaak en manipulatie van LinkedList objects public ListTest() List link = new LinkedList(); List link2 = new LinkedList(); // beide lijsten opvullen for ( int count = 0; count < colors.length; count++ ) { link.add( colors[ count ] ); link2.add( colors2[ count ] ); } JAVA

21 5. Voorbeeld : LINKEDLIST 1
// ‘plak’ link2 achter link1 link.addAll( link2 ); // concatenatie van lists link2 = null; // release resources printList( link ); uppercaseStrings( link ); System.out.print( "\nDeleting elements 4 to 6..." ); removeItems( link, 4, 7 ); printReversedList( link ); } // einde constructor ListTest JAVA

22 5. Voorbeeld : LINKEDLIST 1
public void printList( List list ) {//... } // localiseer String objecten en converteer naar // hoofdletters private void uppercaseStrings( List list ) { ListIterator iterator = list.listIterator(); while ( iterator.hasNext() ) Object object = iterator.next(); // get item if ( object instanceof String ) // check for String iterator.set( ( ( String ) object ).toUpperCase() ); } JAVA

23 5. Voorbeeld : LINKEDLIST 1
// gebruik sublist view om een reeks element te verwijderen //van start tot end-1 private void removeItems( List list, int start, int end ) { list.subList( start, end ).clear(); // verwijder items } // druk de lijst van eind naar begin private void printReversedList( List list ) ListIterator iterator = list.listIterator( list.size() ); System.out.println( "\nReversed List:" ); while( iterator.hasPrevious() ) System.out.print( iterator.previous() + " " ); public static void main( String args[] ) new ListTest(); } // end class ListTest JAVA

24 5. Voorbeeld : LINKEDLIST 1
black yellow green blue violet silver gold white brown blue gray silver BLACK YELLOW GREEN BLUE VIOLET SILVER GOLD WHITE BROWN BLUE GRAY SILVER Deleting elements 4 to 6... BLACK YELLOW GREEN BLUE WHITE BROWN BLUE GRAY SILVER Reversed List: SILVER GRAY BLUE BROWN WHITE BLUE GREEN YELLOW BLACK JAVA

25 5. Voorbeeld : LINKEDLIST 2
import java.util.*; public class UsingToArray { // create LinkedList, add elements and convert to array public UsingToArray() String colors[] = { "black", "blue", "yellow" }; LinkedList links = new LinkedList( Arrays.asList( colors ) ); links.addLast( "red" ); // add als laaste item links.add( "pink" ); // add als laaste item links.add( 3, "green" ); // insert op de 3de index plaats links.addFirst( "cyan" ); // add als eerste item JAVA

26 5. Voorbeeld : LINKEDLIST 2
// get LinkedList elements als een array colors=(String []) links.toArray(new String[ links.size() ]); // ... Levert volgende lijst:cyan, black, blue, yellow, green, red, pink Argument van toArray(Object [] a) - als a te klein is : er wordt een nieuwe array van hetzelfde runtime type aangemaakt. - als a groters is: de meegegeven array wordt gebruikt, de overige originele elementen blijven behouden behalve het element op plaats a[size] wordt null. JAVA

27 Oefening: List Implementaties.
Extra methoden Interface List: void add(int index, Object o); boolean addAll(int index, Collection c); Object get(int index); int indexOf(Object o); lastIndexOf(Object o); ListIterator listIterator(); ListIterator listIterator(int index); Object remove(int index); Object set(int index, Object o); List subList(int fromIndex, int toIndex); Extra methoden LinkedList: LinkedList(); LinkedList(Collection c) ;void addFirst(Object o); void addLast(Object o); Object clone(); Object getFirst(); Object getLast(); Object removeFirst(); Object removeLast(); String toString(); Extra methoden ArrayList: ArrayList(); ArrayList(int initialCapacity); ArrayList(Collection c); Object clone(); void ensureCapacity(int minCapacity); String toString(); void trimToSize(); JAVA

28 Oefening: List Implementaties.
Er zijn een aantal kisten met fruit... Voeg de verschillende kisten samen in een ArrayList list. Verwijder alle fruit dat met de letter ‘p’ begint uit de list. Gebruik hiervoor een eigen klasse CollectionOperaties met een methode verwijderOpLetter. Verwijder alle fruit uit de list vanaf het eerste voorkomen van kiwi tot het laatste voorkomen van kiwi, gebruik eveneens een methode verwijderSequence uit je klasse CollectionOperaties. Plaats het resultaat terug in een array mand en sorteer die oplopend. String kist[][] = { {"appel", "peer", "citroen", "kiwi", "perzik"}, {"banaan", "mango", "citroen", "kiwi", "zespri", "pruim"}, {"peche", "lichi", "kriek", "kers", "papaya"} }; ArrayList list; String mand[]; JAVA

29 Collection algoritmen: min max
Het Collections framework voorziet een aantal algoritmen (static methoden) List algoritmen: sort binarySearch reverse shuffle fill copy Collection algoritmen: min max JAVA

30 6. ALGORITME : sort Sorteervolgorde : wordt bepaald door de implementatie van de bij het object horende compareTo methode. Wordt gedeclareerd in de interface Comparable. Deze sorteervolgorde wordt de ‘natuurlijke ordening’ genoemd. De sorteermethode is ‘stable’, bij gelijke waarden blijft de oorspronkelijke volgorde behouden. Een andere sorteervolgorde verkrijg je door een tweede argument mee te geven : dit is een Comparator object. Voorgedefinieerde comparator objecten. Collections.reverseOrder() Zelfgedefinieerde comparator objecten.

31 6. ALGORITME : sort Volgens natuurlijke ordening:
private static final String suits[] = { "Hearts", "Diamonds", "Clubs", "Spades" }; Volgens natuurlijke ordening: List list = new ArrayList( Arrays.asList( suits ) );//create Collections.sort( list ); // ArrayList Met voorgedefinieerde Comparator (dalend): List list = Arrays.asList( suits ); // create List Collections.sort( list, Collections.reverseOrder() ); Met zelfgedefinieerde Comparator: Een ArrayList van Time2 objecten. public class Time2 //zie hoofdstuk 8. { private int hour, minute, second; //constructors, accessors, mutators, toString ... } JAVA

32 6. ALGORITME : sort : zelfgedefinieerde Comparator.
import java.util.*; public class Sort3 { public void printElements() List list = new ArrayList(); list.add( new Time2( 6, 24, 34 ) ); list.add( new Time2( 18, 14, 05 ) ); list.add( new Time2( 12, 07, 58 ) ); list.add( new Time2( 6, 14, 22 ) ); list.add( new Time2( 8, 05, 00 ) ); // output List elements System.out.println( "Unsorted array elements:\n" + list ); // sort in order using a comparator Collections.sort( list, new TimeComparator() ); System.out.println( "Sorted list elements:\n" + list ); } public static void main( String args[] ) { new Sort3().printElements(); JAVA

33 6. ALGORITME : sort : zelfgedefinieerde Comparator.
private class TimeComparator implements Comparator { int hourCompare, minuteCompare, secondCompare; Time2 time1, time2; public int compare( Object object1, Object object2 ) time1 = ( Time2 ) object1; // cast de objecten naar time2 = ( Time2 ) object2; // werkelijk type hourCompare = new Integer( time1.getHour() ).compareTo( new Integer( time2.getHour() ) ); if ( hourCompare != 0 ) // test het uur eerst return hourCompare; minuteCompare = new Integer( time1.getMinute()).compareTo( new Integer( time2.getMinute() ) ); if ( minuteCompare != 0 ) // dan de minuten return minuteCompare; secondCompare = new Integer( time1.getSecond()).compareTo( new Integer( time2.getSecond() ) ); return secondCompare; // tenslotte de seconden } JAVA

34 • Verdeelt de elementen van een list in een willekeurige volgorde.
6. ALGORITME : shuffle. Unsorted array elements: [06:24:34, 18:14:05, 08:05:00, 12:07:58, 06:14:22] Sorted list elements: [06:14:22, 06:24:34, 08:05:00, 12:07:58, 18:14:05] Algoritme shuffle. • Verdeelt de elementen van een list in een willekeurige volgorde. Voorbeeld: class Card //zie ook hfdst 11.7 { private String face, suit; //...constructor/get/set/toString } JAVA

35 6. ALGORITME : shuffle voorbeeld.
public class Cards { private static final String suits[] = { "Hearts", "Clubs", "Diamonds", "Spades" }; private static final String faces[] ={ "Ace","Deuce","Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" }; private List list; // maak stapel kaarten en schud door elkaar public Cards() Card deck[] = new Card[ 52 ]; for ( int count = 0; count < deck.length; count++ ) deck[ count ] = new Card( faces[ count % 13 ], suits[ count / 13 ] ); list = Arrays.asList( deck ); Collections.shuffle( list ); } //... JAVA

36 6. ALGORITME : reverse, fill, copy, min, max.
import java.util.*; public class Algorithms1 { private String letters[] = { "P", "C", "M" }, lettersCopy[]; private List list, copyList; public Algorithms1() list = Arrays.asList( letters ); // get List lettersCopy = new String[ 3 ]; copyList = Arrays.asList( lettersCopy ); System.out.println( "Initial list: " ); output( list ); Collections.reverse( list ); // reverse order System.out.println("\nAfter calling reverse: "); output(list); JAVA

37 6. ALGORITME : reverse, fill, copy, min, max.
Collections.copy( copyList, list ); //copy List //overschrijft de elementen van copyList :dupliceert // de objecten //als er copyList.size() > list.size(): // overige (laatste) elementen blijven ongewijzigd //als er copyList.size() < list.size(): // IndexOutOfBoundsException System.out.println( "\nAfter copying: " ); output(copyList); Collections.fill( list, "R" ); // fill list with R’s System.out.println( "\nAfter calling fill: " ); output(list); } JAVA

38 6. ALGORITME : reverse, fill, copy, min, max.
private void output( List listRef ) { System.out.print( "The list is: " ); for ( int k = 0; k < listRef.size(); k++ ) System.out.print( listRef.get( k ) + " " ); System.out.print( "\nMax: " + Collections.max( listRef ) ); System.out.println( " Min: " + Collections.min( listRef ) ); }// er is ook een overloaded versie max en min met Comparator public static void main( String args[] ) { new Algorithms1(); } } Initial list: The list is: P C M Max: P Min: C After calling reverse: The list is: M C P After copying: The list is: M C P Max: P Min: C After calling fill: The list is: R R R Max: R Min: R JAVA

39 6. ALGORITME : binarysearch.
Collections.binarySearch(list, key) Zelfde gedrag als bij Arrays Ook overloaded met als derde argument een Comparator. Indien er meerdere gelijke sleutelwaarden zijn is er geen garantie welke sleutel ervan wordt geselecteerd. JAVA

40 Oefening: Algoritme. Methoden Class Collections:
static int binarySearch(List list, Object key); static int binarySearch(List list, Object key, Comparator c); static void copy(List dest, List src); static Enumeration enumeration(Collection c); static void fill(List list, Object obj); static int indexOfSubList(List source, List target); static int lastIndexOfSubList(List source, List target); static ArrayList list(Enumeration e); static Object max(Collection coll); static Object max(Collection coll, Comparator comp); static Object min(Collection coll); static Object min(Collection coll, Comparator comp); static List nCopies(int n, Object o); static boolean replaceAll(List list, Object oldVal, Object newVal); static void reverse(List list); static Comparator reverseOrder(); static void rotate(List list, int distance); static void shuffle(List list); static void shuffle(List list, Random rnd); static Set singleton(Object o); static List singletonList(Object o); static Map singletonMap(Object key, Object value); static void sort(List list); static void sort(List list, Comparator c); static void swap(List list, int i, int j); static Collection synchronizedCollection(Collection c); //ook voor List, Map, Set, SortedMap, SortedSet static Collection unmodifiableCollection(Collection c); //ook voor List, Map, Set, SortedMap, SortedSet JAVA

41 Oefening: Algoritme. Gebruik de ArrayList list van fruit van vorige oef... Sorteer de fruit list oplopend. Voeg een nieuw fruit sapodilla toe aan de lijst. Gebruik hiervoor de methode addOrdered die je toevoegt in je eigen klasse CollectionOperaties. JAVA

42 HashSet is een implementatie- klasse van interface Set.
7. SET INTERFACE. Interface Collection Interface Set Interface SortedSet HashSet is een implementatie- klasse van interface Set. Treeset is een implementatie- klasse van interface SortedSet. JAVA

43 Collectie die unieke elementen bevat. HashSet
7. SET INTERFACE. Collectie die unieke elementen bevat. HashSet Implementatie op basis van hashtabel. Treeset Implementatie op basis van een boomstructuur. Implementeert SortedSet: subinterface van Set. JAVA

44 7. SET : HashSet. // Gebruik HashSet om dubbels te verwijderen.
import java.util.*; public class SetTest { private static final String colors[] = {"red","white","blue", "green", "gray", "orange", "tan", "white", "cyan", "peach", "gray", "orange" }; public SetTest() List list = new ArrayList( Arrays.asList( colors ) ); System.out.println( "ArrayList: " + list ); printNonDuplicates( list ); } JAVA

45 7. SET : HashSet. private void printNonDuplicates( Collection collection ) { Set set = new HashSet( collection ); Iterator iterator = set.iterator(); System.out.println( "\nNonduplicates are: " ); while ( iterator.hasNext() ) System.out.print( iterator.next() + " " ); System.out.println(); } JAVA

46 7. SET : HashSet. public static void main( String args[] ) {
new SetTest(); } ArrayList: [red, white, blue, green, gray, orange, tan, white, cyan, peach, gray, orange] Nonduplicates are: red cyan white tan gray green orange blue peach JAVA

47 7. SET : SortedSet enTreeSet.
import java.util.*; // Gebruik TreeSet om een array te sorteren en dubbels te // elimeneren. // Illustreert ‘range view’ methoden: selectie van een // deel van de Collection public class SortedSetTest { private static final String names[] = { "yellow","green","black","tan","grey", "white","orange","red","green" }; JAVA

48 7. SET : SortedSet enTreeSet.
public SortedSetTest() { SortedSet tree = new TreeSet( Arrays.asList( names ) ); System.out.println( "set: " ); printSet( tree ); // alle elementen die < zijn dan element "orange" System.out.print( "\nheadSet (\"orange\"): " ); printSet( tree.headSet( "orange" ) ); // alle elementen die >= zijn dan element "orange" System.out.print( "tailSet (\"orange\"): " ); printSet( tree.tailSet( "orange" ) ); // het eerste en het laatste element System.out.println( "first: " + tree.first() ); System.out.println( "last : " + tree.last() ); } JAVA

49 7. SET : SortedSet en TreeSet.
private void printSet( SortedSet set ) { Iterator iterator = set.iterator(); while ( iterator.hasNext() ) System.out.print( iterator.next() + " " ); System.out.println(); } public static void main( String args[] ) { new SortedSetTest(); set: black green grey orange red tan white yellow headSet ("orange"): black green grey tailSet ("orange"): orange red tan white yellow first: black last : yellow JAVA

50 HashTable en HashMap zijn implementatie-klassen van Map.
8. MAP INTERFACE. Interface Map Interface SortedMap HashTable en HashMap zijn implementatie-klassen van Map. TreeMap is een implementatie-klasse van SortedMap. JAVA

51 Implementaties van interface Map
8. MAP INTERFACE. Verzameling van key-value paren. Bij elke sleutel hoort precies één waarde. Implementaties van interface Map HashMap Elementen opgeslagen in hashtabel. Laat null key of null values toe. TreeMap Elementen opgeslagen in boomstructuur. Implementatie van SortedMap subinterface van Map. Gebruik de natuurlijke volgorde of een Comparator. JAVA

52 8. MAP : HashMap. // Illustreert het gebruik van een Hashmap:
// Telt het voorkomen van elk woord uit een tekst // (JTextField) en bergt de frequentie tabel op in een // String // creëer een map en vul met de woorden private void createMap() { String input = inputField.getText(); StringTokenizer tokenizer = new StringTokenizer( input ); while ( tokenizer.hasMoreTokens() ) String word = tokenizer.nextToken().toLowerCase(); if ( map.containsKey( word ) ) // als de map het woord bevat Integer count = (Integer) map.get( word ); // get value en map.put(word,new Integer(count.intValue()+1));// verhoog } else // anders voeg nieuw woord toe in map met een value 1 map.put( word, new Integer( 1 ) ); JAVA

53 8. MAP : HashMap. // creëer een string die al de sleutel-waarden koppels van // de map bevat private String createOutput() { StringBuffer output = new StringBuffer( "" ); Iterator keys = map.keySet().iterator(); while ( keys.hasNext() ) // doorloop al de sleutels Object currentKey = keys.next(); output.append( currentKey +"\t"+ map.get(currentKey) + "\n" ); } output.append( "size: " + map.size() + "\n" ); output.append( "isEmpty: " + map.isEmpty() + "\n" ); return output.toString(); JAVA

54 8. MAP : HashMap. JAVA

55 9. SYNCHRONIZATION WRAPPERS.
De collections van het Collections framework zijn unsynchronized. Via synchronization wrapper class converteren we collections tot synchronized versies. public static Collections methoden: Collection synchronizedCollection (Collection c) List synchronizedList( List aList) Set synchronizedSet(Set s) SortedSet synchronizedSortedSet(SortedSet s) Map synchronizedMap(Map m) SortedMap synchronizedSortedMap(SortedMap m) JAVA

56 10. UNMODIFIABLE WRAPPERS.
Convertie naar niet wijzigbare collections. Throw UnsupportedOperationException bij poging tot wijzigen van collectie. public static Collections methoden: Collection unmodifiableCollection (Collection c) List unmodifiableList( List aList) Set unmodifiableSet(Set s) SortedSet unmodifiableSortedSet(SortedSet s) Map unmodifiableMap(Map m) SortedMap unmodifiableSortedMap(SortedMap m) JAVA

57 11. ABSTRACT IMPLEMENTATIONS.
Er zijn abstracte implementaties van de collection interfaces die als basis voor een zelfgedefiniëerde implementatie kunnen dienen. AbstractCollection AbstractList AbstractMap AbstractSequentialList AbstractSet JAVA

58 Oefening: Set en Map. Methode interface Map:
void clear(); boolean containsKey(Object key); boolean containsValue(Object value); Set entrySet() ; boolean equals(Object o); Object get(Object key); int hashCode(); boolean isEmpty(); Set keySet(); Object put(Object key, Object value); void putAll(Map t); Object remove(Object key); int size(); Collection values(); Methoden interface Map.Entry: Boolean equals(Object o); Object getKey(); Object getValue(); int hashCode(); Object setValue(); JAVA

59 Oefening: Set en Map. Berg de fruit list van vorige oefeningen in een boom op zodat dubbels geelimineerd worden. Er moet ook de mogelijkheid zijn de bijhorende prijs (decimale waarde) bij te houden. Doorloop de boom in lexicaal oplopende volgorde en vraag telkens de bijhorende prijs, die je mee in de boom opbergt. Druk vervolgens de volledige lijst in twee kolommen (naam : prijs) in lexicaal oplopende volgorde af op het scherm. JAVA


Download ppt "H 22. COLLECTIONS FRAMEWORK. 1. INLEIDING."

Verwante presentaties


Ads door Google