64
2006 Pearson Education, Inc. All rights rese 1 2 8 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.

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

  • View
    214

  • Download
    0

Embed Size (px)

Citation preview

Page 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

2006 Pearson Education, Inc. All rights reserved.

1

2828

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.

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

2006 Pearson Education, Inc. All rights reserved.

2

28.1 Introduction

28.2   Collections Overview

28.3   Class Array and Enumerators

28.4   Nongeneric Collections

28.4.1 Class ArrayList

28.4.2  Class Stack

28.4.3  Class Hashtable

28.5 Generic Collections

28.5.1 Generic Class SortedDictionary

28.5.2  Generic Class LinkedList

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

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

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

2006 Pearson Education, Inc. All rights reserved.

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

• 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 objects)• E.g. List<T>

•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

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

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

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

2006 Pearson Education, Inc. All rights reserved.

6

Fig. 28.1 | Some common collection interfaces of .NET Framework collections

Interface Description

ICollection The root interface in the collections hierarchy from which interfaces IList and IDictionary inherit. Contains a Count property to determine the size of a collection and a CopyTo method for copying a collection’s contents into a traditional array.

IList An ordered collection that can be manipulated like an array. Provides an indexer for accessing elements with an int index. Also has methods for searching and modifying a collection, including Add, Remove, Contains and IndexOf.

IDictionary A collection of values, indexed by an arbitrary “key” object. Provides an indexer for accessing elements with an object index and methods for modifying the collection (e.g. Add, Remove). IDictionary property Keys contains the objects used as indices, and property Values contains all the stored objects.

IEnumerable An object that can be enumerated. This interface contains exactly one method, GetEnumerator, which returns an IEnumerator object (discussed in Section 28.3). ICollection implements IEnumerable, so all collection classes implement IEnumerable directly or indirectly.

28.2 Collections Overview (Cont.)

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

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

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

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 objects

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

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

2006 Pearson Education, Inc. All rights reserved.

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

• 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

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

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

CCllaassss Implements DDeessccrriippttiioonn

SSyysstteemm nnaammeessppaaccee::

AArrrraayy IILLiisstt TThhee bbaassee ccllaassss ooff aallll ccoonnvveennttiioonnaall aarrrraayyss.. SSeeee SSeeccttiioonn 2288..33..

SSyysstteemm..CCoolllleeccttiioonnss nnaammeessppaaccee::

AArrrraayyLLiisstt IILLiisstt MMiimmiiccss ccoonnvveennttiioonnaall aarrrraayyss,, bbuutt wwiillll ggrrooww oorr sshhrriinnkk aass nneeeeddeedd ttoo aaccccoommmmooddaattee tthhee nnuummbbeerr ooff eelleemmeennttss.. SSeeee SSeeccttiioonn 2288..44..11..

BBiittAArrrraayy IICCoolllleeccttiioonn AA mmeemmoorryy--eeffffiicciieenntt aarrrraayy ooff bboooollss..

HHaasshhttaabbllee IIDDiiccttiioonnaarryy AAnn uunnoorrddeerreedd ccoolllleeccttiioonn ooff kkeeyy––vvaalluuee ppaaiirrss tthhaatt ccaann bbee aacccceesssseedd bbyy kkeeyy.. SSeeee SSeeccttiioonn 2288..44..33..

QQuueeuuee IICCoolllleeccttiioonn AA ffiirrsstt--iinn ffiirrsstt--oouutt ccoolllleeccttiioonn.. SSeeee SSeeccttiioonn 2266..66..

SSoorrtteeddLLiisstt IIDDiiccttiioonnaarryy AA ggeenneerriicc HHaasshhttaabbllee tthhaatt ssoorrttss ddaattaa bbyy kkeeyyss aanndd ccaann bbee aacccceesssseedd eeiitthheerr bbyy kkeeyy oorr bbyy iinnddeexx..

SSttaacckk IICCoolllleeccttiioonn AA llaasstt--iinn,, ffiirrsstt--oouutt ccoolllleeccttiioonn.. SSeeee SSeeccttiioonn 2288..44..22..

Note: All the above non-generic collection classes directly or indirectly implement interfaces ICollection and IEnumerable

++ A QUICK LOOK ++ 28.2 Collections Overview (Cont.)

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

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

Class Implements Description

System.Collections.Generic namespace:

Dictionary< K, V > IDictionary< K, V > A generic, unordered collection of key–value pairs that can be accessed by key.

LinkedList< T > ICollection< T > A doubly linked list. See Section 28.5.2.

List< T > IList< T > A generic ArrayList.

Queue< T > ICollection< T > A generic Queue.

SortedDictionary< K, V >

IDictionary< K, V > A Dictionary that sorts the data by the keys in a binary tree. See Section 28.5.1.

SortedList< K, V > IDictionary< K, V > A generic SortedList.

Stack< T > ICollection< T > A generic Stack.

[Note: All collection classes directly or indirectly implement ICollection and IEnumerable (or the equivalent generic interfaces ICollection< E > and IEnumerable< E > for generic collections).]

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< T > and IEnumerable< T >

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

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

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

2006 Pearson Education, Inc. All rights reserved.

13 1 // Fig. 28.3: UsingArray.cs

2 // Array class static methods for common array manipulations.

3 using System;

4 using System.Collections;

5

6 // demonstrate algorithms of class Array

7 public class UsingArray

8 {

9 private static int[] intValues = { 1, 2, 3, 4, 5, 6 };

10 private static double[] doubleValues = { 8.4, 9.3, 0.2, 7.9, 3.4 };

11 private static int[] intValuesCopy;

12

13 // method Main demonstrates class Array's methods

14 public static void Main( string[] args )

15 {

16 intValuesCopy = new int[ intValues.Length ]; // elements default to 0’s

17

18 Console.WriteLine( "Initial array values:\n" );

19 PrintArrays(); // output initial array contents

20

21 // sort doubleValues

22 Array.Sort( doubleValues );

23

24 // copy intValues into intValuesCopy

25 Array.Copy( intValues, intValuesCopy, intValues.Length );

26

27 Console.WriteLine( "\nArray values after Sort and Copy:\n" );

28 PrintArrays(); // output array contents

29 Console.WriteLine();

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

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

2006 Pearson Education, Inc. All rights reserved.

1430

31 // search for 5 in intValues (it was initialized in sorted order!)

32 int result = Array.BinarySearch( intValues, 5 );

33 if ( result >= 0 )

34 Console.WriteLine( "5 found at element {0} in intValues",

35 result );

36 else

37 Console.WriteLine( "5 not found in intValues" );

38

39 // search for 8763 in intValues

40 result = Array.BinarySearch( intValues, 8763 );

41 if ( result >= 0 )

42 Console.WriteLine( "8763 found at element {0} in intValues",

43 result );

44 else

45 Console.WriteLine( "8763 not found in intValues" );

46 } // end method Main

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

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

2006 Pearson Education, Inc. All rights reserved.

1547

48 // output array content with enumerators

49 private static void PrintArrays()

50 {

51 Console.Write( "doubleValues: " );

52

53 // iterate through the double array with an enumerator

54 IEnumerator enumerator = doubleValues.GetEnumerator();

55 // enumerator now positioned BEFORE first element of doubleValues 56 while ( enumerator.MoveNext() ) // MoveNext returns TRUE when next element exists in coll’n 57 Console.Write( enumerator.Current + " " );

58 // write value of the current element followed by space

59 Console.Write( "\nintValues: " );

60

61 // iterate through the int array with an enumerator 62 enumerator = intValues.GetEnumerator(); //same ‘enumerator’ as declared in l.54 63 // below identical loop despite different type of elements

64 while ( enumerator.MoveNext() )

65 Console.Write( enumerator.Current + " " );

66

67 Console.Write( "\nintValuesCopy: " );

68 69 // iterate through the 2nd int array with a foreach statement – to see // an alternative 70 foreach ( var element in intValuesCopy ) // var is new C# construct - // - an implicitly typed local variable - see p. 350-351(ed.3) 71 Console.Write( element + " " );

72

73 Console.WriteLine();

74 } // end method PrintArrays

75 } // end class UsingArray

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

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

2006 Pearson Education, Inc. All rights reserved.

16

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 5 found at element 4 in intValues 8763 not found in intValues

Outline

UsingArray.cs

(4 of 4)

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

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

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

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

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

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.

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

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

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

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 + " " );

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

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

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

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

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

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), ArrayLists contains strings

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

2006 Pearson Education, Inc. All rights reserved.

25

Fig. 28.4 | Some methods and properties of class ArrayList.

Method or Property Description

Add Adds an object to the ArrayList and returns an int specifying the index at which the object was added.

Capacity Property that gets and sets the number of elements for which space is currently reserved in the ArrayList.

Clear Removes all the elements from the ArrayList.

Contains Returns true if the specified object is in the ArrayList; otherwise, returns false.

Count Read-only property that gets the number of elements stored in the ArrayList.

IndexOf Returns the index of the first occurrence of the specified object in the ArrayList.

Insert Inserts an object at the specified index.

Remove Removes the first occurrence of the specified object.

RemoveAt Removes an object at the specified index.

RemoveRange Removes a specified number of elements starting at a specified index in the ArrayList.

Sort Sorts the ArrayList.

TrimToSize Reduces the Capacity of the ArrayList to the number of elements the ArrayList currently contains (Count).

++ QUICK LOOK ++ Some methods and properties of class ArrayList.

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

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.

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

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

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

2006 Pearson Education, Inc. All rights reserved.

28 1 // Fig. 28.5 (ed.3): ArrayListTest.cs

2 // Using class ArrayList.

3 using System;

4 using System.Collections;

5

6 public class ArrayListTest

7 {

8 private static readonly string[] colors =

9 { "MAGENTA", "RED", "WHITE", "BLUE", "CYAN" };

10 private static readonly string[] removeColors =

11 { "RED", "WHITE", "BLUE" };

12

13 // create ArrayList, add colors to it and manipulate it

14 public static void Main( string[] args )

15 {

16 ArrayList list = new ArrayList( 1 ); // initial capacity of 1

17

18 // add the elements of the colors array to the ArrayList list

19 foreach ( var color in colors )

20 list.Add( color ); // add color to the ArrayList list

21

22 // Add elements in the removeColors array to the removeList

23 // (of type ArrayList) with the ArrayList constructor

24 ArrayList removeList = new ArrayList( removeColors );

Outline

ArrayListTest.cs

(1 of 3)Declare two arrays of strings

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

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

2006 Pearson Education, Inc. All rights reserved.

2925

26 Console.WriteLine( "ArrayList: " );

27 DisplayInformation( list ); // output the list

28

29 // remove from ArrayList list the colors in removeList

30 RemoveColors( list, removeList );

31

32 Console.WriteLine( "\nArrayList after calling RemoveColors: " );

33 DisplayInformation( list ); // output list contents

34 } // end method Main

35

36 // displays information on the contents of an array list

37 private static void DisplayInformation( ArrayList arrayList )

38 {

39 // iterate through array list with a foreach statement

40 foreach ( var element in arrayList )

41 Console.Write( "{0} ", element ); // invokes ToString

42

43 // display the size and capacity

44 Console.WriteLine( "\nSize = {0}; Capacity = {1}",

45 arrayList.Count, arrayList.Capacity );

46 // find position (index) of ‘BLUE’ in the list

47 int index = arrayList.IndexOf( "BLUE" );

48

49 if ( index != -1 )

50 Console.WriteLine( "The array list contains BLUE at index {0}.",

51 index );

52 else

53 Console.WriteLine( "The array list does not contain BLUE." );

54 } // end method DisplayInformation

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.

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

2006 Pearson Education, Inc. All rights reserved.

3055

56 // remove colors specified in secondList from firstList

57 private static void RemoveColors( ArrayList firstList,

58 ArrayList secondList )

59 {

60 // iterate through second ArrayList like an array

61 for ( int count = 0; count < secondList.Count; count++ )

62 firstList.Remove( secondList[ count ] );

63 } // end method RemoveColors

64 } // end class ArrayListTest 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.

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)

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

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 ArrayLists!

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

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

2006 Pearson Education, Inc. All rights reserved.

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

(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 objects

- Value types are implicitly boxed into objects 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

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

2006 Pearson Education, Inc. All rights reserved.

33 1 // Fig. 28.6: StackTest.cs

2 // Demonstrating class Stack.

3 using System;

4 using System.Collections;

5

6 public class StackTest

7 {

8 public static void Main( string[] args )

9 {

10 Stack stack = new Stack(); // Stack from System.Collections;

11 // default Capacity of 10

12 // create objects to store in the stack

13 bool aBoolean = true;

14 char aCharacter = '$';

15 int anInteger = 34567;

16 string aString = "hello";

17

18 // use Push to add items to (the top of) the stack (imlpicit boxing used)

19 stack.Push( aBoolean );

20 PrintStack( stack );

21 stack.Push( aCharacter );

22 PrintStack( stack );

23 stack.Push( anInteger );

24 PrintStack( stack );

25 stack.Push( aString );

26 PrintStack( stack );

27

28 // check the top element of the stack

29 Console.WriteLine( "The top element of the stack is {0}\n",

30 stack.Peek() );

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

 

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

2006 Pearson Education, Inc. All rights reserved.

3431

32 // remove items from stack

33 try

34 {

35 while ( true ) // Loop broken only by an exception

36 {

37 object removedObject = stack.Pop();

38 Console.WriteLine( removedObject + " popped" );

39 PrintStack( stack );

40 } // end while

41 } // end try

42 catch ( InvalidOperationException exception )

43 {

44 // if exception occurs, output stack trace

45 Console.Error.WriteLine( exception );

46 } // end catch

47 } // end Main

48

49 // Display the contents of a stack

50 private static void PrintStack( Stack stack )

51 {

52 if ( stack.Count == 0 )

53 Console.WriteLine( "stack is empty\n" ); // the stack is empty

54 else

55 {

56 Console.Write( "The stack is: " );

57

58 // iterate through the stack with a foreach statement

59 foreach ( var element in stack )

60 Console.Write( "{0} ", element ); // invokes implicitly ToString

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

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

2006 Pearson Education, Inc. All rights reserved.

3561

62 Console.WriteLine( "\n" );

63 } // end else

64 } // end method PrintStack

65 } // end class StackTest 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 hello popped The stack is: 34567 $ True 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

Outline

StackTest.cs

(3 of 3)

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

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.

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

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

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

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

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

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

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

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

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

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

Enter a string:

As idle as a painted ship upon a painted ocean Hashtable contains: Key: Value: painted 2 a 2 upon 1 as 2 ship 1 idle 1 ocean 1 size: 7

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

2006 Pearson Education, Inc. All rights reserved.

42

1 // Fig. 27.7: HashtableTest.cs

2 // Application counts the number of occurrences of each word in a string

3 // and stores them in a hash table.

4 using System;

5 using System.Text.RegularExpressions;

6 using System.Collections;

7

8 public class HashtableTest

9 {

10 public static void Main( string[] args )

11 {

12 // create hash table based on user input

13 Hashtable table = CollectWords(); // CollectWords() defind in l. 20+

14

15 // display hash table content

16 DisplayHashtable( table ); // DisplayHashtable(…) defind in l. 49+

17 } // end method Main

18

19 // create hash table from user input

20 private static Hashtable CollectWords()

21 {

22 Hashtable table = new Hashtable(); // create a new hash table

23

24 Console.WriteLine( "Enter a string: " ); // prompt for user input

25 string input = Console.ReadLine(); // get input

26

27 // split input text into tokens (tokens are words here)

28 string[] words = Regex.Split( input, @"\s+" );

Outline

HashtableTest.cs

(1 of 3)

Create Hashtables

Divide the user’s input by its whitespace characters

++ SKIP ++

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

2006 Pearson Education, Inc. All rights reserved.

43

29

30 // processing input words

31 foreach ( var word in words )

32 {

33 string wordKey = word.ToLower(); // get word in lowercase

34

35 // if the hash table contains the word

36 if ( table.ContainsKey( wordKey ) )

37 { 38 table[ wordKey ] = ( ( int ) table[ wordKey ] ) + 1; // (1) explicit downcast (unbox) from “object” to “int” // (2) increase the count for wordkey // (3) implicit re-boxing of int into object – a table[] element 39 } // end if

40 else

41 // add new word with a count of 1 to hash table 42 table.Add( wordKey, 1 ); // implicit boxing of “1” into object // (objects stored by method Add) 43 } // end foreach

44

45 return table;

46 } // end method CollectWords

47

48 // display hash table content

49 private static void DisplayHashtable( Hashtable table )

50 {

51 Console.WriteLine( "\nHashtable contains:\n{0,-12}{1,-12}",

52 "Key:", "Value:" ); // ‘-‘ means left justified, 12 is field width

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

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

2006 Pearson Education, Inc. All rights reserved.

44

53

54 // generate output for each key in hash table

55 // by iterating through the Keys property with a foreach statement

56 foreach ( var key in table.Keys )

57 Console.WriteLine( "{0,-12}{1,-12}", key, table[ key ] ); // “0” and “1”

58 // are placeholders for arguments, “12” is output width, “-“ in “-12’ means: “left justified”

59 Console.WriteLine( "\nsize: {0}", table.Count );

60 } // end method DisplayHashtable

61 } // end class HashtableTest

Enter a string:

As idle as a painted ship upon a painted ocean Hashtable contains: Key: Value: painted 2 a 2 upon 1 as 2 ship 1 idle 1 ocean 1 size: 7

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

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

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.

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

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

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

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

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

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

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

2006 Pearson Education, Inc. All rights reserved.

49

Enter a string: We few, we happy few, we band of brothers Sorted dictionary contains: Key: Value: band 1 brothers 1 few, 2 happy 1 of 1 we 3 size: 6

++ 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 < K, V >

(not nongeneric collection Hashtable)

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

2006 Pearson Education, Inc. All rights reserved.

50 1 // Fig. 27.8 (ed.2): SortedDictionaryTest.cs

2 // Application counts the number of occurrences of each word in a string

3 // and stores them in a generic sorted dictionary.

4 using System;

5 using System.Text.RegularExpressions;

6 using System.Collections.Generic;

7

8 public class SortedDictionaryTest

9 {

10 public static void Main( string[] args )

11 {

12 // create sorted dictionary based on user input

13 SortedDictionary< string, int > dictionary = CollectWords(); // cf. l. 20+

14 // key/value of type string/int, resp.

15 // display sorted dictionary content

16 DisplayDictionary( dictionary ); // cf. l. 51+

17 } // end method Main

18

19 // create sorted dictionary from user input

20 private static SortedDictionary< string, int > CollectWords()

21 {

22 // create a new sorted dictionary

23 SortedDictionary< string, int > dictionary =

24 new SortedDictionary< string, int >();

25

26 Console.WriteLine( "Enter a string: " ); // prompt for user input

27 string input = Console.ReadLine(); // get input

28

29 // split input text into tokens

30 string[] words = Regex.Split( input, @"\s+" );

Outline

SortedDictionaryTest.cs

(1 of 3)

Namespace that contains class SortedDictionary

Create a dictionary of int values keyed with strings

Split the user’s input using its whitespace characters

++ SKIP ++

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

2006 Pearson Education, Inc. All rights reserved.

51

31

32 // processing input words

33 foreach ( var word in words )

34 {

35 string wordKey = word.ToLower(); // get word in lowercase

36

37 // if the dictionary contains the word

38 if ( dictionary.ContainsKey( wordKey ) )

39 { 40 ++dictionary[ wordKey ]; // no downcasting (unboxing) of int! // Because we declared: SortedDictionary< string, int> dictionary (l.13) 41 } // end if

42 else

43 // add new word with a count of 1 to the dictionary

44 dictionary.Add( wordKey, 1 ); // no boxing! (same reason as l.40)

45 } // end foreach

46

47 return dictionary;

48 } // end method CollectWords

49

50 // display dictionary content

51 private static void DisplayDictionary< K, V >(

52 SortedDictionary< K, V > dictionary )

53 {

54 Console.WriteLine( "\nSorted dictionary contains:\n{0,-12}{1,-12}",

55 "Key:", "Value:" )

Outline

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

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

2006 Pearson Education, Inc. All rights reserved.

5256

57 // generate output for each key in the sorted dictionary

58 // by iterating through the Keys property with a foreach statement

59 foreach ( K key in dictionary.Keys )

60 Console.WriteLine( "{0,-12}{1,-12}", key, dictionary[ key ] );

61

62 Console.WriteLine( "\nsize: {0}", dictionary.Count );

63 } // end method DisplayDictionary

64 } // end class SortedDictionaryTest

Enter a string: We few, we happy few, we band of brothers Sorted dictionary contains: Key: Value: band 1 brothers 1 few, 2 happy 1 of 1 we 3 size: 6

Outline

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

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

2006 Pearson Education, Inc. All rights reserved.

53

++ SKIP ++ Performance Tip 28.6

ClassSortedDictionary 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

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

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.

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

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)

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

2006 Pearson Education, Inc. All rights reserved.

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

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

2006 Pearson Education, Inc. All rights reserved.

5728.5 Generic Collections (Cont.)

Linked list: black yellow green blue violet silver gold white brown blue gray Converting strings in list1 to uppercase Linked list: BLACK YELLOW GREEN BLUE VIOLET SILVER GOLD WHITE BROWN BLUE GRAY Deleting strings between BLACK and BROWN Linked list: BLACK BROWN BLUE GRAY Reversed List: GRAY BLUE BROWN BLACK

• I/O behavior for the next program- Uses generic collection LinkedList< T >

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

2006 Pearson Education, Inc. All rights reserved.

58 1 // Fig. 28.9(ed.3): LinkedListTest.cs

2 // Using LinkedLists.

3 using System;

4 using System.Collections.Generic;

5

6 public class LinkedListTest

7 {

8 private static readonly string[] colors = { "black", "yellow",

9 "green", "blue", "violet", "silver" };

10 private static readonly string[] colors2 = { "gold", "white",

11 "brown", "blue", "gray" };

12

13 // set up and manipulate LinkedList objects

14 public static void Main( string[] args )

15 {

16 LinkedList< string > list1 = new LinkedList< string >();

17

18 // add elements to first linked list

19 foreach ( var color in colors )

20 list1.AddLast( color );

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 strings

Create a generic LinkedList of type string

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

2006 Pearson Education, Inc. All rights reserved.

5921

22 // add elements to second linked list via constructor

23 LinkedList< string > list2 = new LinkedList< string >( colors2 );

24

25 Concatenate( list1, list2 ); // concatenate list2 onto list1

26 PrintList( list1 ); // display list1 elements

27

28 Console.WriteLine( "\nConverting strings in list1 to uppercase\n" );

29 ToUppercaseStrings( list1 ); // convert to uppercase string

30 PrintList( list1 ); // display list1 elements

31

32 Console.WriteLine( "\nDeleting strings between BLACK and BROWN\n" );

33 RemoveItemsBetween( list1, "BLACK", "BROWN" );

34

35 PrintList( list1 ); // display list1 elements

36 PrintReversedList( list1 ); // display list in reverse order

37 } // end method Main

38

39 // output list contents

40 private static void PrintList< T >( LinkedList< T > list )

41 {

42 Console.WriteLine( "Linked list: " );

43

44 foreach ( T value in list )

45 Console.Write( "{0} ", value );

46

47 Console.WriteLine();

48 } // end method PrintList

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<E> iterates

and outputs the values of the LinkedList

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

2006 Pearson Education, Inc. All rights reserved.

6049

50 // concatenate the second list on the end of the first list

51 private static void Concatenate< T >( LinkedList< T > list1,

52 LinkedList< T > list2 )

53 {

54 // concatenate lists by copying element values

55 // in order from the second list to the first list

56 foreach ( T value in list2 )

57 list1.AddLast( value ); // add new node

58 } // end method Concatenate

59

60 // locate string objects and convert to uppercase

61 private static void ToUppercaseStrings( LinkedList< string > list )

62 {

63 // iterate over the list by using the nodes

64 LinkedListNode< string > currentNode = list.First;

65

66 while ( currentNode != null )

67 {

68 string color = currentNode.Value; // get value from node

69 currentNode.Value = color.ToUpper(); // convert to uppercase

70

71 currentNode = currentNode.Next; // get next node

72 } // end while

73 } // end method ToUppercaseStrings

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 strings to uppercase

Traverse to the next LinkedListNode

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

2006 Pearson Education, Inc. All rights reserved.

6174

75 // delete list items between two given items (do not remove the two items)

76 private static void RemoveItemsBetween< T >( LinkedList< T > list,

77 T startItem, T endItem )

78 {

79 // get the nodes corresponding to the start and end item

80 LinkedListNode< T > currentNode = list.Find( startItem );

81 LinkedListNode< T > endNode = list.Find( endItem );

82

83 // remove items after the start item

84 // until we find the last item or the end of the linked list

85 while ( ( currentNode.Next != null ) &&

86 ( currentNode.Next != endNode ) )

87 {

88 list.Remove( currentNode.Next ); // remove next node

89 } // end while

90 } // end method RemoveItemsBetween

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)

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

2006 Pearson Education, Inc. All rights reserved.

62

96

97 // iterate over the list by using the nodes

98 LinkedListNode< T > currentNode = list.Last;

99

100 while ( currentNode != null )

101 {

102 Console.Write( "{0} ", currentNode.Value );

103 currentNode = currentNode.Previous; // get previous node

104 } // end while

105

106 Console.WriteLine();

107 } // end method PrintReversedList

108 } // end class LinkedListTest

Linked list: black yellow green blue violet silver gold white brown blue gray Converting strings in list1 to uppercase Linked list: BLACK YELLOW GREEN BLUE VIOLET SILVER GOLD WHITE BROWN BLUE GRAY Deleting strings between BLACK and BROWN Linked list: BLACK BROWN BLUE GRAY Reversed List: GRAY BLUE BROWN BLACK

Outline

LinkedListTest.cs

(5 of 5)

Property to obtain the last LinkedListNode

Traverse to the previous LinkedListNode(it is a doubly-linked list)

91

92 // print reversed list

93 private static void PrintReversedList< T >( LinkedList< T > list )

94 {

95 Console.WriteLine( "Reversed List:" );

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

2006 Pearson Education, Inc. All rights reserved.

63

The End of Ch 28 - Collections

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

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