1 / 56

Modul 3

Modul 3. Collections af objekter Arraylist Collections Objektorienteret design og Java. 4.0. Main concepts to be covered. Collections (especially ArrayList ). The requirement to group objects. Many applications involve collections of objects: Personal organizers. Library catalogs.

leif
Download Presentation

Modul 3

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Modul 3 Collections af objekter Arraylist Collections Objektorienteret design og Java. 4.0

  2. Main concepts to be covered • Collections(especially ArrayList) Modul 3

  3. The requirement to group objects • Many applications involve collections of objects: • Personal organizers. • Library catalogs. • Student-record system. • The number of items to be stored varies. • Items added. • Items deleted. Modul 3

  4. A personal notebook • Notes may be stored. • Individual notes can be viewed. • There is no limit to the number of notes. • It will tell how many notes are stored. • Explore the notebook1 project. Modul 3

  5. Take a quick look at notebook1 • Explore the notebook1 project. Modul 3

  6. Class libraries • Collections of useful classes. • We don’t have to write everything from scratch. • Java calls its libraries, packages. • Grouping objects is a recurring requirement. • The java.util package contains classes for doing this. Modul 3

  7. Importing Class libraries import java.util.ArrayList; /** * ... */ public class Notebook { // Storage for an arbitrary number of notes. private ArrayList<String> notes; /** * Perform any initialization required for the * notebook. */ public Notebook() { notes = new ArrayList<String>(); } ... } Module 3

  8. Collections • We specify: • the type of collection: ArrayList • the type of objects it will contain: <String> • We say, “ArrayList of String”. Modul 3

  9. Object structures with collections Modul 3

  10. Adding a third note Modul 3

  11. Features of the collection • It increases its capacity as necessary. • It keeps a private count (size()accessor). • It keeps the objects in order. • Details of how all this is done are hidden. • Does that matter? Does not knowing how prevent us from using it? Modul 3

  12. Using the collection public class Notebook { private ArrayList<String> notes; ... public void storeNote(String note) { notes.add(note); } public int numberOfNotes() { return notes.size(); } ... } Adding a new note Returning the number of notes (delegation) Modul 3

  13. Index numbering Modul 3

  14. Retrieving an object Index validity checks public void showNote(int noteNumber) { if(noteNumber < 0) { // This is not a valid note number. } else if(noteNumber < numberOfNotes()) { System.out.println(notes.get(noteNumber)); } else { // This is not a valid note number. } } Retrieve and print the note Modul 3

  15. Removal may affect numbering Modul 3

  16. Generic classes • Collections are known as parameterized or generic types. • ArrayList implements list functionality: • add, get, size, etc. • The type parameter says what we want a list of: • ArrayList<Person> • ArrayList<TicketMachine> • etc. Modul 3

  17. Review • Collections allow an arbitrary number of objects to be stored. • Class libraries usually contain tried-and-tested collection classes. • Java’s class libraries are called packages. • We have used the ArrayList class from the java.util package. Modul 3

  18. Review • Items may be added and removed. • Each item has an index. • Index values may change if items are removed (or further items added). • The main ArrayList methods are add, get, remove and size. • ArrayList is a parameterized or generic type. Modul 3

  19. Some Collections types • java.util.ArrayList • java.util.LinkedList • java.util.Vector • java.util.Stack • List • Set • SortedSet • NavigableSet • Map • Queue • java.util.EnumSet • java.util.HashSet • java.util.LinkedHashSet • java.util.TreeSet • java.util.SortedSet • java.util.HashMap • java.util.Hashtable • java.util.EnumMap • java.util.IdentityHashMap • java.util.LinkedHashMap • java.util.Properties • java.util.TreeMap • java.util.WeakHashMap • java.util.NavigableSet • java.util.LinkedList • java.util.PriorityQueue Modul 3

  20. Grouping objects Collections and the for-each loop

  21. Interlude:Some popular errors... Først en kviklille test Modul 3

  22. /** * Print out notebook info (number of entries). */public void showStatus(){ if(notes.size() == 0); {System.out.println(“Notebook is empty”); } else {System.out.print(“Notebook holds “);System.out.println(notes.size() + “ notes); }} What’s wrong here? Modul 3

  23. /** * Print out notebook info (number of entries). */public void showStatus(){ if(notes.size() == 0); {System.out.println(“Notebook is empty”); } else {System.out.print(“Notebook holds “);System.out.println(notes.size() + “ notes); }} This is the same as before! Modul 3

  24. This is the same again /** * Print out notebook info (number of entries). */public void showStatus(){ if(notes.size() == 0) ; {System.out.println(“Notebook is empty”); } else {System.out.print(“Notebook holds “);System.out.println(notes.size() + “ notes); }} Modul 3

  25. /** * Print out notebook info (number of entries). */public void showStatus(){ if(notes.size() == 0) { ; } {System.out.println(“Notebook is empty”); } else {System.out.print(“Notebook holds “);System.out.println(notes.size() + “ notes); }} and the same again… Modul 3

  26. /** * Print out notebook info (number of entries). */public void showStatus(){ if(isEmpty = true) {System.out.println(“Notebook is empty”); } else {System.out.print(“Notebook holds “);System.out.println(notes.size() + “ notes); }} This time I have a boolean field called ‘isEmpty’... What’s wrong here? Modul 3

  27. /** * Print out notebook info (number of entries). */public void showStatus(){ if(isEmpty == true) {System.out.println(“Notebook is empty”); } else {System.out.print(“Notebook holds “);System.out.println(notes.size() + “ notes); }} This time I have a boolean field called ‘isEmpty’... The correct version Modul 3

  28. /** * Store a new note in the notebook. If the * notebook is full, save it and start a new one. */public void addNote(String note){ if(notes.size() == 100)notes.save();// starting new notebook notes = new ArrayList<String>();notes.add(note);} What’s wrong here? Modul 3

  29. /** * Store a new note in the notebook. If the * notebook is full, save it and start a new one. */public void addNote(String note){ if(notes.size == 100)notes.save();// starting new notebook notes = new ArrayList<String>();notes.add(note);} This is the same. Modul 3

  30. /** * Store a new note in the notebook. If the * notebook is full, save it and start a new one. */public void addNote(String note){ if(notes.size == 100) {notes.save();// starting new notebook notes = new ArrayList<String>(); }notes.add(note);} The correct version Modul 3

  31. Main concepts to be covered • Collections • Loops: the for-each loop Modul 3

  32. Iteration • We often want to perform some actions an arbitrary number of times. • E.g., print all the notes in the notebook. How many are there? • Most programming languages include loop statements to make this possible. • Java has several sorts of loop statement. • We will start with its for-each loop. Modul 3

  33. Iteration fundamentals • We often want to repeat some actions over and over. • Loops provide us with a way to control how many times we repeat those actions. • With collections, we often want to repeat things once for every object in a particular collection. Modul 3

  34. For-each loop pseudo code General form of the for-each loop forkeyword loop header for(ElementType element : collection) { loop body } Statement(s) to be repeated Pseudo-code expression of the actions of a for-each loop For each element in collection, do the things in the loop body. Modul 3

  35. A Java example /** * List all notes in the notebook. */ public void listNotes() { for(String note : notes) { System.out.println(note); } } for each note in notes, print out note Modul 3

  36. Review • Loop statements allow a block of statements to be repeated. • The for-each loop allows iteration over a whole collection. Modul 3

  37. Grouping objects The while loop

  38. Main concepts to be covered • The while loop Moduil 3

  39. The while loop • A for-each loop repeats the loop body for each object in a collection. • Sometimes we require more variation than this. • We can use a boolean condition to decide whether or not to keep going. • A while loop provides this control. Modul 3

  40. While loop pseudo code General form of a while loop whilekeyword boolean test while(loop condition) { loop body } Statements to be repeated Pseudo-code expression of the actions of a while loop while we wish to continue, do the things in the loop body Modul 3

  41. A Java example /** * List all notes in the notebook. */ public void listNotes() { int index = 0; while(index < notes.size()) { System.out.println(notes.get(index)); index++; } } Increment index by 1 while the value of index is less than the size of the collection, print the next note, and then increment index Modul 3

  42. for-each versus while • for-each: • easier to write. • safer: it is guaranteed to stop. • while: • we don’t have to process the whole collection. • doesn’t even have to be used with a collection. • take care: could be an infinite loop. Modul 3

  43. While without a collection // Print all even numbers from 0 to 30. int index = 0; while(index <= 30) { System.out.println(index); index = index + 2; } Modul 3

  44. Searching a collection int index = 0; boolean found = false; while(index < notes.size() && !found) { String note = notes.get(index); if(note.contains(searchString)) { // We don't need to keep looking. found = true; } else { index++; } } // Either we found it, or we searched the whole // collection. Modul 3

  45. Grouping objects Iterators

  46. Main concepts to be covered • Iterators Modul 3

  47. :Iterator myList:List myList.iterator() :Element :Element :Element :Element Modul 3

  48. :Iterator :Iterator myList:List :Element :Element :Element :Element ✔ hasNext()? next() Element e = iterator.next(); Modul 3

  49. :Iterator :Iterator myList:List :Element :Element :Element :Element ✔ hasNext()? next() Modul 3

  50. :Iterator :Iterator myList:List :Element :Element :Element :Element ✔ hasNext()? next() Modul 3

More Related