Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2006 Pearson Education, Inc. All rights reserved. 1 28 Collections Many slides modified by Prof. L. Lilien (even many without an explicit message indicating.

Similar presentations


Presentation on theme: " 2006 Pearson Education, Inc. All rights reserved. 1 28 Collections Many slides modified by Prof. L. Lilien (even many without an explicit message indicating."— Presentation transcript:

1  2006 Pearson Education, Inc. All rights reserved. 1 28 Collections Many slides modified by Prof. L. Lilien (even many without an explicit message indicating an update). Slides added or modified by L.Lilien are © 2006-2009 Leszek T. Lilien. Permision to use for non-commercial purposes slides added by L.Lilien’s will be gladly granted upon a written (e.g., emailed) request.

2  2006 Pearson Education, Inc. All rights reserved. 2 28.1Introduction 28.2 Collections Overview 28.3 Class Array and Enumerators 28.4 Nongeneric Collections 28.4.1Class ArrayList 28.4.2 Class Stack 28.4.3 Class Hashtable 28.5Generic Collections 28.5.1Generic Class SortedDictionary 28.5.2 Generic Class LinkedList

3  2006 Pearson Education, Inc. All rights reserved. 3 28.1 Introduction. NET Framework Collections a.k.a. collection classes -Prepackaged data-structure classes Store collections of data -Functions of collection classes Enable programmers to store sets of items by using existing data structures -Need not concern how they are implemented Are example of code reuse Allow programmers to code faster and assure excellent performance -Maximizing execution speed and minimizing memory consumption Written by experts to provide such speed and efficiency

4  2006 Pearson Education, Inc. All rights reserved. 4 28.1 Introduction (Cont.).NET Framework Collections – cont. -The.NET Framework provides three namespaces dedicated to collections: System.Collections namespace -Contains collections that store references to object s object is the top-level object in C# -Used mainly by legacy code Easy since any object in C# is-a object System.Collections.Generic namespace -Contains generic classes to store collections of types specified by user They store references to these types (not references to object s) E.g. List System.Collections.Specialized namespace -Contains several collections that support specific types They support only these specific types E.g.: collections to support strings and bits

5  2006 Pearson Education, Inc. All rights reserved. 5 28.2 Collections Overview Collection Implements some combination of collection interfaces Collection interface -Declares the operations to be performed generically on various types of collections implementing the collection interface Recall: An interface declares the operations (methods) to be performed generically on various types of implementations of the interface -Next figure: Some collection interfaces of.NET Framework collections All declared in System.Collections

6  2006 Pearson Education, Inc. All rights reserved. 6 Fig. 28.1 | Some common collection interfaces of.NET Framework collections 28.2 Collections Overview (Cont.)

7  2006 Pearson Education, Inc. All rights reserved. 7 28.2 Collections Overview (Cont.) All above non-generic collection interfaces from.NET Framework (declared in System.Collections) have generic analogs (which are generic collection interfaces) declared in System.Collections.Generic

8  2006 Pearson Education, Inc. All rights reserved. 8 28.2 Collections Overview (Cont.) Earlier versions of collection classes stored/manipulated object references -Could store any object reference in a collection -Retrieving object references from a collection required downcast to an appropriate type Necessary to allow the application to process the object s correctly We can do better (than storing object references) by using generic classes from the namespace System.Collections.Generic -These generic classes are generic counterparts of the (non-generic) classes from the namespace System.Collections

9  2006 Pearson Education, Inc. All rights reserved. 9 28.2 Collections Overview (Cont.) Using System.Collections.Generic -You can specify the exact type to be stored in a collection -Now, the object (object, not object !) retrieved from a collection has a correct type No need for explicit type casts -So no overhead of explicit casting - Improve efficiency Generic collections are esp. useful for storing structs -Bec. eliminate need for boxing/unboxing Next 2 slides are a quick look at: -7 (non-generic) collection classes for object s 1 from the namespace System, 6 from the namespace System.Collections -7 generic collection classes All from the namespace System.Collections.Generic -No specialized collection classes from the namespace System.Collections.Specialized

10  2006 Pearson Education, Inc. All rights reserved. 10 Fig. 28.2-Part 1 | Some non-generic collection classes of the.NET Framework. (Part 1 of 2.) Note: All the above non-generic collection classes directly or indirectly implement interfaces ICollection and IEnumerable ++ A QUICK LOOK ++ 28.2 Collections Overview (Cont.)

11  2006 Pearson Education, Inc. All rights reserved. 11 Fig. 28.2 –Part 2 | Some generic collection classes of the.NET Framework. (Part 2 of 2.) Notes: 1) Namespace System.Collections.Specialized is NOT shown in the table above. 2) Collection classes can create enumerators that allow to walk through the collections. Enumerators implement (differently) the IEnumerator interface. ++ A QUICK LOOK ++ 28.2 Collections Overview (Cont.) Note: All the generic collection casses directly or indirectly implement generic interfaces ICollection and IEnumerable

12  2006 Pearson Education, Inc. All rights reserved. 12 28.3 Class Array and Enumerators Abstract class Array (namespace: System ) -All arrays implicitly inherit from this abstract base class Defines property Length -Specifies the number of elements in the array Provides static methods that provide algorithms for processing arrays -E.g. (cf. Lines 22, 25, 32, resp. on next slide): Array.Sort( …) Array.Copy ( … ) Array.BinarySearch (…) (notice upper case A indicates static () -For a complete list of class Array ’s methods visit: msdn2.microsoft.com/en-us/library/system.array.aspx

13  2006 Pearson Education, Inc. All rights reserved. 13 Outline UsingArray.cs (1 of 4) Declare three static array variables Initialize intValuesCopy as the same size as intValues Sort the array doubleValues in ascending order Copy elements from array intValues to array intValuesCopy Initial array values: doubleValues: 8.4 9.3 0.2 7.9 3.4 intValues: 1 2 3 4 5 6 intValuesCopy: 0 0 0 0 0 0 Array values after Sort and Copy: doubleValues: 0.2 3.4 7.9 8.4 9.3 intValues: 1 2 3 4 5 6 intValuesCopy: 1 2 3 4 5 6

14  2006 Pearson Education, Inc. All rights reserved. 14 Outline UsingArray.cs (2 of 4) Perform binary searches on array intValues CRITICAL: binary search requires sorted array as input. We can use BinarySearch on intValues since it is sorted at the moment (actually, it is sorted since initialization in Line 9) 5 found at element 4 in intValues 8763 not found in intValues

15  2006 Pearson Education, Inc. All rights reserved. 15 Outline UsingArray.cs (3 of 4) Obtains an enumerator for the corresponding array Advances the enumerator for the corresponding array Obtains and output the current array element (Current is read-only property) Iterate over the collection elements like an enumerator (implemented via enumerator!) [Example output produced by PrintArrays() – already shown on Slide “-2”; repeated here for convenience] doubleValues: 0.2 3.4 7.9 8.4 9.3 intValues: 1 2 3 4 5 6 intValuesCopy: 1 2 3 4 5 6

16  2006 Pearson Education, Inc. All rights reserved. 16 Outline UsingArray.cs (4 of 4)

17  2006 Pearson Education, Inc. All rights reserved. 17 ++ READ LATER++ 28.3 Class Array and Enumerators (Cont.) Array methods used in the above code - Sort Sort array Returns the array containing its original elements sorted in ascending order - Copy Copy elements from an array to another 1st argument is the source array (the array to copy from) 2nd argument is the destination array (the array to copy to) 3rd argument is an int representing the number of elements to copy - BinarySearch Perform binary searches on array Input: a sorted array in which to search and the key for which to search (WATCH OUT!!! If input array unsorted: GIGO) Returns the index in the array at which it finds the key

18  2006 Pearson Education, Inc. All rights reserved. 18 ++ READ LATER++ 28.3 Class Array and Enumerators (Cont.) Other Array methods — not used in the above code - Clear Set a range of elements to 0 or null - CreateInstance Create a new array of a specified type - IndexOf Locate the first occurrence of an object in an array or portion of an array - LastIndexOf Locate the last occurrence of an object in an array or portion of an array - Reverse Reverse the contents of an array or portion of an array

19  2006 Pearson Education, Inc. All rights reserved. 19 ++ READ LATER++ Common Programming Error 28.1 Passing an unsorted array to BinarySearch is a logic error—the value returned is undefined.

20  2006 Pearson Education, Inc. All rights reserved. 20 ++ READ LATER++ 28.3 Class Array and Enumerators (Cont.) Enumerators - Array implements the interface IEnumerable IEnumerable Method GetEnumerator -Obtains an enumerator for an array - Array implements the interface IEnumerator (different from the above IEnumerable!) Method MoveNext -Moves the enumerator to the next element in the collection -Returns true if there is at least one more element in the collection Method Reset -Positions the enumerator before the first element of the collection Property Current -Returns the object at the current location in the collection Note on methods MoveNext and Reset -Throws an InvalidOperationException If the contents of the collection are modified in any way after the enumerator is created

21  2006 Pearson Education, Inc. All rights reserved. 21 ++ READ LATER++ 28.3 Class Array and Enumerators (Cont.) foreach Statement -Implicitly obtains an enumerator Via the GetEnumerator method -Implicitly uses the enumerator’s MoveNext method and Current property to traverse the collection -Able to iterate over any collection that implements the IEnumerable interface RECALL: Use of var - an implicitly typed local variable -New C# construct — see pp. 350-351(ed.3) -Example: var used for int array (few slides back) : foreach ( var element in intValuesCopy ) Console.Write( element + " " );

22  2006 Pearson Education, Inc. All rights reserved. 22 ++ READ LATER++ Common Programming Error 28.2 If a collection is modified after an enumerator is created for that collection, the enumerator immediately becomes invalid—any methods called with the enumerator after this point throw InvalidOperationExceptions. (After a collection modified, must re-create its enumerator before using it.) For this reason, enumerators are said to be “fail fast.”

23  2006 Pearson Education, Inc. All rights reserved. 23 28.4 Non-generic Collections Primary source for non-generic collections: namespace System.Collections Classes from System.Collections provide: - Standard implementations of many of the data structures discussed in class (Ch.26) -Non-generic collections that store references of type object

24  2006 Pearson Education, Inc. All rights reserved. 24 28.4 Non-generic Collections (Cont.) 28.4.1 Class ArrayList Class ArrayList -Mimics the functionality of conventional arrays -Provides dynamic resizing of the collection through the class’s methods Property Capacity -Manipulate the capacity of the ArrayList -When ArrayList needs to grow, it by default doubles its Capacity - ArrayList stores references to objects of the type object Can contain objects of any type -Since all classes derive from class object -In Example of Fig. 28.5 (below), ArrayList s contains strings

25  2006 Pearson Education, Inc. All rights reserved. 25 Fig. 28.4 | Some methods and properties of class ArrayList. ++ QUICK LOOK ++ Some methods and properties of class ArrayList.

26  2006 Pearson Education, Inc. All rights reserved. 26 ++ READ LATER++ Performance Tips 28.1 and 28.2 Tip 28.1: As with linked lists, inserting additional elements into an ArrayList whose current size is less than its capacity is a fast operation. Tip 28.2: Inserting an element into an ArrayList that needs to grow larger to accommodate a new element is a slow operation. Reason: An ArrayList that is at its capacity must have its memory reallocated and the existing values copied into it.

27  2006 Pearson Education, Inc. All rights reserved. 27 ++ READ LATER++ Performance Tip 28.3 If storage is at a premium, use method TrimToSize of class ArrayList to trim an ArrayList to its exact size. - This will optimize an ArrayList ’s memory use. - Be careful—if the application needs to insert additional elements, the process will be slower because the ArrayList must grow dynamically (trimming leaves no room for growth).

28  2006 Pearson Education, Inc. All rights reserved. 28 Outline ArrayListTest.cs (1 of 3) Declare two arrays of string s Create an ArrayList with an initial capacity of 1 element Add one-by-one the five elements of array colors to list Use overloaded constructor to create a new ArrayList initialized with the contents of array removeColors

29  2006 Pearson Education, Inc. All rights reserved. 29 Outline ArrayListTest.cs (2 of 3) Iterate through arrayList to output its elements Display the current number of elements and capacity (the maximum number of elements that can be stored without allocating more memory) Determine the position of the string “BLUE” in arrayList ArrayList: MAGENTA RED WHITE BLUE CYAN Size = 5; Capacity = 8 The array list contains BLUE at index 3. ArrayList after calling RemoveColors: MAGENTA CYAN Size = 2; Capacity = 8 The array list does not contain BLUE.

30  2006 Pearson Education, Inc. All rights reserved. 30 Outline ArrayListTest.cs (3 of 3) Use the indexer (by using [count]) to obtain each of secondList ’s elements and remove it from firstList (in turn, removes: “RED”, “WHITE” and “BLUE” (at index 0, 1, and 2 in secondList set to removeColors )

31  2006 Pearson Education, Inc. All rights reserved. 31 ++ READ LATER++ Performance Tip 28.4 ArrayList methods IndexOf and Contains each perform a linear search, - A very expensive operation for large ArrayList s! If ArrayList is sorted, use ArrayList ‘s method BinarySearch for a more efficient search. Method BinarySearch returns the index of the element, or a negative number if the element is not found So, can substitute for both IndexOf and Contains

32  2006 Pearson Education, Inc. All rights reserved. 32 28.4 Non-generic Collections (Cont.) 28.4.2. Class Stack Class Stack (from the System.Collections namespace – cf. Fig. 28.2) -Method Push Takes and inserts an object of type object to the top of the Stack Grows to accommodate more object s (stack never overflows in this implementation) -Grows when the number of items on the Stack (the Count property) is equal to the capacity at the time of the Push operation Can store only references to object s -Value types are implicitly boxed into object s before they are added -Method Pop Removes and returns the object (of type object) currently on the top of Stack -Method Peek (not implemented by us in the ‘Data Structures’ Chapter) Returns the value of the top stack element Does not remove the element from the Stack -Note on methods Pop and Peek Throws InvalidOperationException if the Stack is empty -Property Count (not implemented by us in the ‘Data Structures’ Chapter) Obtain the number of elements in Stack

33  2006 Pearson Education, Inc. All rights reserved. 33 Outline StackTest.cs (1 of 3) Create a stack with the default initial capacity of 10 elements Add four elements to the stack Obtain the value of the top stack element (without popping it off the stack). The stack is: True The stack is: $ True The stack is: 34567 $ True The stack is: hello 34567 $ True The top element of the stack is hello

34  2006 Pearson Education, Inc. All rights reserved. 34 Outline StackTest.cs (2 of 3) Obtain and remove the value of the top stack element (implicit unboxing used) Use foreach statement to iterate over the stack and output its contents 34567 popped The stack is: $ True $ popped The stack is: True True popped stack is empty System.InvalidOperationException: Stack empty. at System.Collections.Stack.Pop() at StackTest.Main(String[] args) in C:\examples\ch27\ fig27_06\StackTest\StackTest.cs:line 37

35  2006 Pearson Education, Inc. All rights reserved. 35 Outline StackTest.cs (3 of 3)

36  2006 Pearson Education, Inc. All rights reserved. 36 ++ READ LATER++ Common Programming Error 28.3 Attempting to Peek or Pop an empty Stack (a Stack whose Count property is 0 ) causes an InvalidOperationException.

37  2006 Pearson Education, Inc. All rights reserved. 37 ++ SKIP ++ 28.4 Non-generic Collections (Cont.) 28.4.3 Class HashTable Class HashTable -Hashing Convert the application key rapidly to an index Example: -250 employees => 250 employee records with key = SSN -Convert SSNs into indices (subscripts) of an array with 250 elements (indices: 0-249) Each number in the range 0 – 999,999,999 (i.e., a SSN) must be “hashed” (converted) into numbers in the range 0-249 Then information (related to the key) could be stored at (and later retrieved from) the location indicated by that index in the array -E.g., record for employee with SSN = 123-45-6789 hashed into index: 147 Data for hashing is stored in a data structure called a hash table Hashing converts a key into an array subscript - Literally scrambles the bits

38  2006 Pearson Education, Inc. All rights reserved. 38 ++ SKIP ++ 28.4 Non-generic Collections (Cont.) Collisions: >= 2different keys “hash into” the same cell in the array -Solution 1: “Hash again” Hashing process is designed to be quite random -Assumption: within a few hashes, an available cell will be found -Solution 2: “Search successive cells” Use hash once to locate the cell. If the cell is occupied, successive cells are searched linearly until an available cell is found Retrieval works in the same way -The key is hashed once, the resulting cell is checked to determine whether it contains the desired data - If it does, the search is complete - If it does not, successive cells are searched linearly until the desired data is found -Solution 3: “Use hash buckets” Each cell of the hash table is a hash “bucket” of all the key–value pairs that hash to that cell Typically, bucket implemented as a linked list -.NET Framework’s Hashtable class implements this solution

39  2006 Pearson Education, Inc. All rights reserved. 39 ++ SKIP ++ 28.4 Non-generic Collections (Cont.) -Load factor The ratio of the number of objects stored in the hash table to its capacity (= the total number of cells in the hash table) Affects the performance of hashing schemes -The load ratio increases => probability of collisions increases -Hash function Calculates where to place data in the hash table -Maps application key into hash table bucket Applied to the key in a key–value pair of objects -Class Hashtable can accept any object as a key (Top-level) class object defines method GetHashCode => Inherited by all objects

40  2006 Pearson Education, Inc. All rights reserved. ++ SKIP ++ Performance Tip 28.5 The load factor in a hash table is a classic example of a space/time trade-off:  By increasing the load factor, we get better memory utilization, but the application runs slower due to increased hashing collisions  By decreasing the load factor, application runs faster because of reduced hashing collisions, but we get worse memory utilization because a larger portion of the hash table remains empty. 40

41  2006 Pearson Education, Inc. All rights reserved. 41 ++ SKIP ++ 28.4 Non-generic Collections (Cont.) I/O behavior for the next program -Uses nongeneric collection Hashtable

42  2006 Pearson Education, Inc. All rights reserved. 42 Outline HashtableTest.cs (1 of 3) Create Hashtable s Divide the user’s input by its whitespace characters ++ SKIP ++

43  2006 Pearson Education, Inc. All rights reserved. 43 Outline HashtableTest.cs (2 of 3) Convert each word to lowercase Determine if the word is in the hash table Use indexer to obtain and then increment the key’s associated value Create a new entry in the hash table and set its value to 1 (boxing of “1” done) ++ SKIP ++

44  2006 Pearson Education, Inc. All rights reserved. 44 Outline HashtableTest.cs (3 of 3) Get an ICollection that contains all the keys Iterate through the hash table and output its elements Note: Hash table is NOT sorted! ++ SKIP ++

45  2006 Pearson Education, Inc. All rights reserved. 45 ++ SKIP ++ Common Programming Error 28.4 Using the Add method to add a key that already exists in the hash table causes an ArgumentException.

46  2006 Pearson Education, Inc. All rights reserved. 46 ++ SKIP ++ 28.4 Non-generic Collections (Cont.) Class Hashtable -Method ContainsKey Determine whether a given word is in the hash table -Property Keys Get an ICollection of all keys that exist in the hash table -Property Value Gets an ICollection of all values stored in the hash table -Property Count Get the number of key-value pairs in the hash table

47  2006 Pearson Education, Inc. All rights reserved. 47 ++ SKIP ++ 28.4 Non-generic Collections (Cont.) Problems with nongeneric collections - Hashtable stores its keys and data as object references We stored only string keys and int values by conversion (boxing) -Inefficient! (explicit unboxing in l.38/implicit boxing – both in l.38 & 42) -Cannot “redundantly” control what is being put into the Hashtable by programmer Programmer might think that she put int value while by mistake she put string value (cf. p. 1400/-4 [ed.3]) No “redundant” compile-time check is run InvalidCastException will be thrown at execution time only Solution: use generic collections

48  2006 Pearson Education, Inc. All rights reserved. 48 28.5 Generic Collections ++ SKIP ++ 28.5.1 Generic Class SortedDictionary Generic Class SortedDictionary -Dictionary A general term for a collection of key–value pairs -A hash table is one way to implement a dictionary -Does not use a hash table Stores its key–value pairs in a binary search tree -Entries are stored in a binary search tree sorted by the key value Using the IComparable interface -Despite different implementation details, SortedDictionary uses the same public methods, properties and indexers as the class Hashtable -Takes two type arguments delimited by The first specifies the type of key The second specifies the type of value

49  2006 Pearson Education, Inc. All rights reserved. 49 ++ SKIP ++ 28.5 Generic Collections (Cont.) I/O behavior for the next program -Similar behavior as for previous program but different implementation -Uses generic collection SortedDictionary (not nongeneric collection Hashtable )

50  2006 Pearson Education, Inc. All rights reserved. 50 Outline SortedDictionary Test.cs (1 of 3) Namespace that contains class SortedDictionary Create a dictionary of int values keyed with string s Split the user’s input using its whitespace characters ++ SKIP ++

51  2006 Pearson Education, Inc. All rights reserved. 51 Outline SortedDictionary Test.cs (2 of 3) Convert each word to lowercase Determine if the word is in the dictionary Use indexer to obtain and set the key’s associated value If no such word in dictionary yet, create a new entry in the dictionary and set its value to 1 Modified to be completely generic; takes type parameters K and V ++ SKIP ++

52  2006 Pearson Education, Inc. All rights reserved. 52 Outline SortedDictionary Test.cs (3 of 3) Get an ICollection that contains all the keys Iterate through the dictionary and output its elements Output the number of different words ++ SKIP ++

53  2006 Pearson Education, Inc. All rights reserved. 53 ++ SKIP ++ Performance Tip 28.6 Class SortedDictionary keeps its elements sorted in a binary tree Therefore, obtaining or inserting a key–value pair takes O(log n) time O(log n) is fast compared to linear searching then inserting

54  2006 Pearson Education, Inc. All rights reserved. 54 ++ SKIP ++ Common Programming Error 28.5 Invoking the get accessor of a SortedDictionary indexer with a key that does not exist in the collection causes a KeyNotFoundException. This behavior is different from that of the Hashtable indexer’s get accessor, which would return null.

55  2006 Pearson Education, Inc. All rights reserved. 55 28.5 Generic Collections (Cont.) 28.5.2 Generic Class LinkedList Generic Class LinkedList -Doubly-linked list -Each node contains: Property Value -Matches LinkedList ’s single type parameter Contains the data stored in the node Read-only property Previous -Gets a reference to the preceding node (or null if the node is the first of the list) Read-only property Next -Gets a reference to the subsequent reference (or null if the node is the last of the list)

56  2006 Pearson Education, Inc. All rights reserved. 56 28.5 Generic Collections (Cont.) Methods in Generic Class LinkedList -Method AddLast Creates a new LinkedListNode Appends this node to the end of the list -Method AddFirst Inserts a node at the beginning of the list -Method Find Performs a linear search on the list (slow!) Returns the first node that contains a value equal to the passed argument -Returns null if the value is not found -Method Remove Splices that node out of the LinkedList Fixes the references of the surrounding nodes so the list remains doubly- linked One LinkedListNode can be a member of no more than one LinkedList Attempt to add a node from one LinkedList to another LinkedList generates an InvalidOperationException

57  2006 Pearson Education, Inc. All rights reserved. 57 28.5 Generic Collections (Cont.) I/O behavior for the next program -Uses generic collection LinkedList

58  2006 Pearson Education, Inc. All rights reserved. 58 Outline LinkedListTest.cs (1 of 5) Create and append nodes of array color ’s elements to the end of the linked list Declare two arrays of string s Create a generic LinkedList of type string

59  2006 Pearson Education, Inc. All rights reserved. 59 Outline LinkedListTest.cs (2 of 5) Use overloaded constructor to create a new LinkedList initialized with the contents of array color2 The generic method PrintList iterates and outputs the values of the LinkedList

60  2006 Pearson Education, Inc. All rights reserved. 60 Outline LinkedListTest.cs (3 of 5) Append each value of list2 to the end of list1 Takes in a LinkedList of type string Property to obtain the first LinkedListNode Convert each of the string s to uppercase Traverse to the next LinkedListNode

61  2006 Pearson Education, Inc. All rights reserved. 61 Outline LinkedListTest.cs (4 of 5) Obtain the “boundaries” nodes of the range Remove one node at a time (and fix the references of the surrounding nodes)

62  2006 Pearson Education, Inc. All rights reserved. 62 Outline LinkedListTest.cs (5 of 5) Property to obtain the last LinkedListNode Traverse to the previous LinkedListNode (it is a doubly-linked list)

63  2006 Pearson Education, Inc. All rights reserved. 63 The End of Ch 28 - Collections

64  2006 Pearson Education, Inc. All rights reserved. 64 ***SKIP – threads not covered in CS1120 *** 27.6(ed.2) Synchronized Collections Synchronization with Collections -Most non-generic collections are unsynchronized Concurrent access to a collection by multiple threads may cause errors -Synchronization wrappers Prevent potential threading problems Used for many of the collections that might be accessed by multiple threads Wrapper object receives method calls, adds thread synchronization, and passes the calls to the wrapped collection object -Most of the non-generic collection classes provide static method Synchronized Returns a synchronized wrapping object for the specified object ArrayList notSafeList = new ArrayList (); ArrayList threadSafeList = ArrayList.Synchronized ( notSafeList ); -The collections in the.NET Framework do not all provide wrappers for safe performance under multiple threads -Using an enumerator is not thread-safe Other threads may change the collection foreach statement is not thread-safe either Use the lock keyword to prevent other threads from using the collection Use a try statement to catch the InvalidOperationException


Download ppt " 2006 Pearson Education, Inc. All rights reserved. 1 28 Collections Many slides modified by Prof. L. Lilien (even many without an explicit message indicating."

Similar presentations


Ads by Google