H 22. COLLECTIONS FRAMEWORK. 1. - PowerPoint PPT Presentation

About This Presentation
Title:

H 22. COLLECTIONS FRAMEWORK. 1.

Description:

H 22. COLLECTIONS FRAMEWORK. 1. INLEIDING. Collections framework Meest voorkomende datastructuren gestandaardiseerd en efficient ge mplementeerd. – PowerPoint PPT presentation

Number of Views:60
Avg rating:3.0/5.0
Slides: 60
Provided by: Klav7
Category:

less

Transcript and Presenter's Notes

Title: H 22. COLLECTIONS FRAMEWORK. 1.


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

2
2. OVERZICHT COLLECTIONS FRAMEWORK
  • Collection
  • 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
  • Collection
  • Set
  • List
  • Map

3
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

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 7s
  • Arrays.fill( filledInt, 7 )
  • // sorteer doubleValues in oplopende volgorde
  • Arrays.sort( doubleValues )
  • // copy array intValues naar array intValuesCopy
  • System.arraycopy( intValues, 0,
    intValuesCopy,

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.

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
//... //...
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)

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 gt toIndex
  • ArrayIndexOutOfBoundsException
  • if fromIndex lt 0 of toIndex gt a.length
  • Idem voor char, byte, short, long, float, double
    en object

9
3. CLASS ARRAYS overloaded methoden
  • static void sort(int a)
  • static void sort(int a, int fromIndex,
    int toIndex)
  • IllegalArgumentException if fromIndex gt toIndex
  • ArrayIndexOutOfBoundsException
  • if fromIndex lt 0 of toIndex gt 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.

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
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 lt list.size() count )
System.out.print( list.get( count ) " " )
System.out.print( "\nArray elements " )
for ( int count 0 count lt 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
12
4. INTERFACE COLLECTION EN CLASS COLLECTIONS.
  • Interface Collection
  • 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

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

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

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).

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)

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 lt colors.length count )
list.add( colors count ) // van string
objecten list.add( Color.CYAN )
// van color object
18
5. Voorbeeld ARRAYLIST
// afdrukken System.out.println(
"\nArrayList " ) for ( int count 0
count lt 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 " )
for ( int count 0 count lt list.size()
count ) System.out.print( list.get(
count ) " " )
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.Colorr255,g0,b255 red
white blue java.awt.Color r0,g255,b255   Arra
yList after calling removeStrings java.awt.Color
r255,g0,b255 java.awt.Colorr0,g255,b255
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 lt colors.length
count ) link.add( colors count )
link2.add( colors2 count )
21
5. Voorbeeld LINKEDLIST 1
// plak link2 achter link1 link.addAll(
link2 ) // concatenatie van lists
link2 null // release
resources printList( link )
uppercaseStrings( link ) printList( link
) System.out.print( "\nDeleting elements 4
to 6..." ) removeItems( link, 4, 7 )
printList( link ) printReversedList( link
) // einde constructor ListTest
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() )
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
24
5. Voorbeeld LINKEDLIST 1
list black yellow green blue violet silver gold
white brown blue gray silver   list BLACK YELLOW
GREEN BLUE VIOLET SILVER GOLD WHITE BROWN BLUE
GRAY SILVER   Deleting elements 4 to
6... list BLACK YELLOW GREEN BLUE WHITE BROWN
BLUE GRAY SILVER   Reversed List SILVER GRAY
BLUE BROWN WHITE BLUE GREEN YELLOW BLACK
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

26
5. Voorbeeld LINKEDLIST 2
// get LinkedList elements als een array
colors(String ) links.toArray(new String
links.size() ) // ... Levert volgende
lijstcyan, 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 asize wordt null.
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()
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

29
6. ALGORITME
  • Het Collections framework voorziet een aantal
    algoritmen (static methoden)
  • List algoritmen
  • sort
  • binarySearch
  • reverse
  • shuffle
  • fill
  • copy
  • Collection algoritmen
  • min
  • max

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
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 ...
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() )
// output List elements System.out.println(
"Sorted list elements\n" list )
public static void main( String args ) new
Sort3().printElements()
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
34
6. ALGORITME shuffle.
Unsorted array elements 062434, 181405,
080500, 120758, 061422 Sorted list
elements 061422, 062434, 080500,
120758, 181405
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
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 lt deck.length count )
deck count new Card( faces count 13 ,
suits count / 13 ) list
Arrays.asList( deck ) Collections.shuffle(
list ) //...
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)

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() gt list.size() // overige
(laatste) elementen blijven ongewijzigd //als
er copyList.size() lt list.size() //
IndexOutOfBoundsException System.out.println(
"\nAfter copying " ) output(copyList)
Collections.fill( list, "R" ) // fill list
with Rs System.out.println( "\nAfter calling
fill " ) output(list)
38
6. ALGORITME reverse, fill, copy, min, max.
private void output( List listRef )
System.out.print( "The list is " ) for (
int k 0 k lt 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 Max P Min C
  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
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.

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
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.

42
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.

43
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.

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 )
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()
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
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"
48
7. SET SortedSet enTreeSet.
public SortedSetTest() SortedSet tree
new TreeSet( Arrays.asList( names ) )
System.out.println( "set " ) printSet( tree
) // alle elementen die lt zijn dan element
"orange" System.out.print( "\nheadSet
(\"orange\") " ) printSet( tree.headSet(
"orange" ) ) // alle elementen die gt 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() )
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
50
8. MAP INTERFACE.
  • Interface Map
  • Interface SortedMap
  • HashTable en HashMap zijn implementatie-klassen
    van Map.
  • TreeMap is een implementatie-klasse van
    SortedMap.

51
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.

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 ) )
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()
54
8. MAP HashMap.
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)

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)

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

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()
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.
Write a Comment
User Comments (0)
About PowerShow.com