1 / 31

Java Collections

Java Collections. M. Taimoor Khan taimoorkhan@ciit-attock.edu.pk (Adapted from Swinburne notes). Learning Objectives. Students can explain why some objects need to hold collections of other objects Students can write code to support this relationship Students should be able to

onella
Download Presentation

Java Collections

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. Java Collections M. Taimoor Khan taimoorkhan@ciit-attock.edu.pk (Adapted from Swinburne notes)

  2. Learning Objectives • Students can explain why some objects need to hold collections of other objects • Students can write code to support this relationship • Students should be able to • Search through collections • Add and remove items form collections • Create objects to manage collections of other objects • Students should be able to use iterators effectively

  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.

  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.

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

  6. java.util • “Contains the collections framework…date and time facilities,… string tokenizer.. random-number generator..” • ArrayList<E>, LinkedList<E>, Stack<E> • Calendar, Date • Formatter • Scanner • StringTokenizer • Random • Iterator<E>

  7. 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>(); } ... }

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

  9. Object structures with collections

  10. Adding a third note

  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?

  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)

  13. Index numbering

  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 < notes.size()) { System.out.println(notes.get(noteNumber)); } else { // This is not a valid note number. } } Retrieve and print the note

  15. Removal may affect numbering

  16. ArrayListimplements list functionality: • add, get, size, etc. • The type parameter says what we want a list of: • ArrayList<Person> • ArrayList<TicketMachine> • etc. Interesting tutorial on generics http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

  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.

  18. Iteration • With collections, we often want to repeat things once for every object in a particular collection. • Most programming languages include loop statements to make this possible. • Java supports • “do”, “while” and various “for” loops • There is also a type called an “iterator”

  19. for loop 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

  20. While loop 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

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

  22. :Iterator myList:List Iterators :Element :Element :Element :Element Ask myList for an iterator myList.iterator()

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

  24. :Iterator :Iterator myList:List :Element :Element :Element :Element ✔ hasNext()? next()

  25. :Iterator :Iterator myList:List :Element :Element :Element :Element ✔ hasNext()? next()

  26. :Iterator :Iterator myList:List :Element :Element :Element :Element ✔ hasNext()? next()

  27. :Iterator myList:List :Element :Element :Element :Element ✗ hasNext()?

  28. Using an Iterator object returns an Iterator object java.util.Iterator Iterator<ElementType> it = myCollection.iterator(); while(it.hasNext()) { call it.next() to get the next object do something with that object } public void listNotes() { Iterator<String> it = notes.iterator(); while(it.hasNext()) { System.out.println(it.next()); } }

  29. Index versus Iterator • Ways to iterate over a collection: • for-each loop. • Use if we want to process every element. • while loop. • Use if we might want to stop part way through. • Use for repetition that doesn't involve a collection. • Iterator object. • Use if we might want to stop part way through. • Often used with collections where indexed access is not very efficient, or impossible. • Iteration is an important programming pattern.

  30. Review • Loop statements allow a block of statements to be repeated. • The for-each loop allows iteration over a whole collection. • The while loop allows the repetition to be controlled by a boolean expression. • All collection classes provide special Iterator objects that provide sequential access to a whole collection.

  31. Reading & Exercises • page 77 – page 86 • page 88 – page 127 • http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html • Exercises will be specified in the lab handout. • Everything to the end of chapter 3 will be assessable in the first test

More Related