Presentation is loading. Please wait.

Presentation is loading. Please wait.

SD2054 Software Development. The Limitation of Arrays Once an array is created it must be sized, and this size is fixed!

Similar presentations


Presentation on theme: "SD2054 Software Development. The Limitation of Arrays Once an array is created it must be sized, and this size is fixed!"— Presentation transcript:

1 SD2054 Software Development

2

3

4

5 The Limitation of Arrays Once an array is created it must be sized, and this size is fixed!

6 An array contains no useful pre- defined methods!

7 Use the classes provided in the Java Collections Framework!

8 By the end of this lecture you should be able to: use the ArrayList class to store a list of objects; use the HashSet class to store a set of objects use the HashMap class to store objects in a map; fix the type of elements within a collection using the generics mechanism; use objects of your own classes in conjunction with Java's collection classes. The Java Collections Framework

9 The classes in the JCF are all found in the java.util package. import java.util.*

10 Three important interfaces from this group are: List Set Map

11 The List interface The List interface specifies the methods required to process an ordered list of objects. Such a list may contain duplicates.

12 The List interface Two implementations provided : ArrayList & LinkedList

13 Using an ArrayList to store a queue of jobs waiting for a printer

14 The ArrayList constructor creates an empty list: ArrayList printQ = new ArrayList();

15 ArrayList printQ = new ArrayList (); Whats that stuff in angled brackets?

16 Its a new Java feature called generics! The ArrayList constructor creates an empty list: ArrayList printQ = new ArrayList ();

17 Use the interface type instead of the implementation type!

18 List printQ = new ArrayList (); A method that receives a printQ object, would now be declared as follows public void someMethod (List printQIn) { // some code here }

19 List printQ = new ArrayList (); A method that receives a printQ object, would now be declared as follows public void someMethod (List printQIn) { // some code here }

20 List printQ = new HashList (); A method that receives a printQ object, would now be declared as follows public void someMethod (List printQIn) { // some code here }

21 List methods - add printQ.add("myLetter.doc"); myLetter.doc printQ printQ.add("myFoto.jpg"); printQ.add("results.xls"); printQ.add("chapter.doc"); myFoto.jpgresults.xlschapter.doc 0123

22 List methods - toString All the Java collection types have a toString method defined System.out.println(printQ); Lists are displayed as follows. [myLetter.doc, myFoto.jpg, results.xls, chapter.doc]

23 List methods – add revisited printQ.add(0, "importantMemo.doc"); printQ myLetter.docmyFoto.jpgresults.xlschapter.doc importantMemo.doc 0123 0 1 234

24 List methods – set myLetter.docmyFoto.jpgresults.xlschapter.docimportantMemo.doc printQ.set(4, "newChapter.doc"); newChapter.doc printQ 01234

25 List methods – size printQ.set(printQ.size()-1, "newChapter.doc"); myLetter.docmyFoto.jpgresults.xlschapter.docimportantMemo.doc newChapter.doc printQ 01234

26 List methods – indexOf Example: finding myFoto.jpg int index = printQ.indexOf("myFoto.jpg"); if (index != -1) { System.out.println("myFoto.jpg is at index position: " + index); } else { System.out.println("myFoto.jpg not in list"); }

27 List methods – remove Example : removing "myFoto.jpg" myFoto.jpg myLetter.docimportantMemo.docresults.xlschapter.doc newChapter.doc printQ printQ.remove(2); printQ.remove("myFoto.jpg"); 0123423

28 List methods – get System.out.println("First job is " + printQ.get(0)); myLetter.docmyFoto.jpgresults.xlschapter.docimportantMemo.doc newChapter.doc printQ First job is importantMemo.doc 01234

29 List methods – contains if (printQ.contains(poem.doc)) { System.out.println(poem.doc is in the list); } else { System.out.println(poem.doc is not in the list); }

30 Using the enhanced for loop with collection classes

31 Example: Iterating through the printQ list to find and display those jobs that end with a.doc extension: for (String item: printQ) { if (item.endsWith(".doc")) { System.out.println(item); } }

32 The Set interface The Set interface defines the methods required to process a collection of objects in which there is no repetition, and ordering is unimportant.

33 Which of these are sets? a queue of people waiting to see a doctor:

34 Which of these are sets? a list of number one records for each of the 52 weeks of a particular year :

35 Which of these are sets? car registration numbers allocated parking permits. AK346NY QC771OD AZ885JL

36 There are 2 implementations provided for the Set interface in the JCF. They are HashSet and TreeSet.

37 Using a HashSet to store a collection of vehicle registration numbers AK346NY QC771OD AZ885JL

38 The constructor creates an empty set: Set regNums = new HashSet();

39 Set regNums = new HashSet (); Remember: use the interface type! The constructor creates an empty set:

40 Set regNums = new HashSet (); Remember: use generics! The constructor creates an empty set:

41 Set methods - add The add method allows us to insert objects into the set regNums.add(V53PLS); regNums.add(X85ADZ); regNums.add(L22SBG); regNums.add(W79TRV);

42 Set methods - toString We can display the entire set as follows: System.out.println(regNums); The set is displayed in the same format as a list: [W79TRV, X85ADZ, V53PLS, L22SBG]

43 Set methods - size As with a list, the size method returns the number of items in the set System.out.println(Number of items in set: + regNums.size() );

44 Set methods - remove The remove method deletes an item from the set if it is present. regNums.remove(X85ADZ); If we now display the set, the given registration will have been removed: [W79TRV, V53PLS, L22SBG]

45 Set interface also includes contains & isEmpty methods

46 Using the enhanced for loop to iterate through a set

47 The following enhanced for loop will allow us to iterate through the registration numbers and display all registrations after T. for (String item: regNums) { if (item.charAt(0)> 'T') { System.out.println(item); } } [W79TRV, V53PLS, L22SBG] W79TRV V53PLS

48 Iterator objects

49 An Iterator object allows the items in a collection to be retrieved by providing three methods defined in the Iterator interface: Methods of the Iterator interface MethodDescriptionInputsOutputs hasNext Returns true if there are more elements in the collection to retrieve and false otherwise. NoneAn item of type boolean. next Retrieves one element from the collection. NoneAn item of the given element type. remove Removes from the collection the element that is currently retrieved None

50 To obtain an Iterator object from a set, call the iterator method.. Iterator elements = regNums.iterator();

51 Using an Iterator object with a 'while' loop..

52 The following removes all registration prior to and including 'T' Iterator elements = regNums.iterator(); while (elements.hasNext()) { String item = elements.next(); if (item.charAt(0)<= 'T') { elements.remove(); } }

53 The Map interface The Map interface defines the methods required to process a collection consisting of pairs of objects (keys and values). 00165328670 BookISBN

54 The Map interface The Map interface defines the methods required to process a collection consisting of pairs of objects (keys and values). NH03456 Patient NHS number

55 The Map interface There are two implementations provided for the Map interface. They are HashMap and TreeMap

56 Using a HashMap to store a collection of user names and passwords usernamepassword LauraHaliwellmonkey SunaGuventelevision BobbyMannelephant LucyLanemonkey BernardAndersonvelvet

57 The constructor creates the empty map: Map users; users = new HashMap( );

58 Map users; users = new HashMap ( ); Remember: use the interface type!

59 The constructor creates the empty map: Map users; users = new HashMap ( ); Remember: use generics!

60 The constructor creates the empty map: Map users; users = new HashMap ( ); KEY type

61 The constructor creates the empty map: Map users; users = new HashMap ( ); VALUE type

62 Map methods - put users.put(LauraHaliwell", monkey"); users LauraHaliwell " monkey"

63 Map methods - put users.put(LauraHaliwell", popcorn"); users LauraHaliwell "monkey"popcorn"

64 users.put(CharlieSheen", crazy"); users LauraHaliwell "popcorn" Map methods - put CharlieSheen " crazy"

65 Map methods - containsKey The containsKey method accepts an object and returns true if the object is a key in the map and false otherwise: if (users.containsKey(LauraHaliwell")) { System.out.println(user ID already taken); } There is also a containsValue method to check for the presence of a value in a map.

66 Map methods - get String password = users.get(LauraHaliwell); if (password != null) { // valid key } else // no such user { System.out.println ("INVALID USERNAME!"); }

67 Map methods - toString Maps are displayed in the following output: {LauraHaliwell=popcorn, CharlieSheen=crazy, BobbyMann=elephant}

68 Map methods - remove The remove method accepts a key value and, if the key is present in the map, both the key and value pair are removed: users.remove(LauraHaliwell"); Displaying the map now shows the users ID and password have been removed: {CharlieSheen=crazy, BobbyMann=elephant }

69 Iterating over the elements of a map In order to scan the items in the map, the keySet method can be used to return the set of keys. Set theKeys = users.keySet(); The set of keys can then be processed in the ways discussed previously for sets.

70 Using your own classes with Javas collection classes

71 The constructor creates an empty set: Set books = new HashSet();

72 When storing user-defined objects in any of the JCF collections, these objects should have three specific methods defined: toString equals hashCode

73 Defining a toString method Here is one possible toString method we could provide for our Book class: public String toString() { return "(" + isbn +", "+ author + ", " + title +")\n"; }

74 Defining an equals method One possible interpretation of two books being equal is simply that their ISBNs are equal, so the following equals method could be added to the Book class: public boolean equals (Object objIn) { } Book bookIn = objIn; Wrong type!

75 Defining an equals method public boolean equals (Object objIn) { } Book bookIn = (Book) objIn; return isbn.equals(bookIn.isbn); One possible interpretation of two books being equal is simply that their ISBNs are equal, so the following equals method could be added to the Book class:

76 The hashCode method The hashCode method returns an integer value from an object. What number can I generate from a book?

77 The hashCode method The hashCode method returns an integer value from an object. How about using the number of pages!

78 The hashCode method The hashCode method returns an integer value from an object. 212

79 The hashCode method The hashCode method returns an integer value from an object. OK, whats the point of this number?

80 The hashCode method The hashCode method returns an integer value from an object. The number makes it quicker to find items!

81 The hashCode method

82 212 244

83 The hashCode method All of Javas predefined classes (such as String) have a meaningful hashCode method defined. For Book equality we check the ISBN only. This ISBN is a String, so all we need to do is to return the hashCode number of this String:

84 The hashCode method public int hashCode() { return isbn.hashCode(); }

85


Download ppt "SD2054 Software Development. The Limitation of Arrays Once an array is created it must be sized, and this size is fixed!"

Similar presentations


Ads by Google