Monday, 22 September 2014

Java Class Libraries


  • Java the platform contains around 4,000
    • classes/interfaces
    • Data Structures
    • Networking, Files
    • Graphical User Interfaces
    • Security and Encryption
    • Image Processing
    • Multimedia authoring/playback And more...
  •  All neatly(ish) arranged into packages (see API docs)
    • Important chunk of the class library
    • A collection is some sort of grouping of things (objects)
    • Usually when we have some grouping we want to go through it (“iterate over it”)
    • The Collections framework has two main interfaces: Iterable and Collections. 
    • They define a set of operations that all classes in the Collections framework support
    • add(Object o), clear(), isEmpty(), etc.
  • <<interface>> Set
    • Like a mathematical set in DM 1
    • A collection of elements with no duplicates
    • Various concrete classes like TreeSet (which keeps the set elements sorted)
  •  <<interface>> List
    • An ordered collection of elements that may contain duplicates
    • ArrayList, Vector, LinkedList, etc.
  • <<interface>> Queue
    • An ordered collection of elements that may contain duplicates and supports
    • removal of elements from the head of the queue
    • PriorityQueue, LinkedLIst, etc.
  • <<interface>> Map
    • Like relations in DM 1, or dictionaries in ML
    • Maps key objects to value objects
    • Keys must be unique
    • Values can be duplicated and (sometimes) null.
  • for loop
    • LinkedList list = new LinkedList();
    • for (int i=0; i<list.size(); i++) {
    • Object next = list.get(i);
    • }
  • foreach loop (Java 5.0+)
    • LinkedList list = new LinkedList();
    • for (Object o : list) {
    • }
  • What if our loop changes the structure?
    • for (int i=0; i<list.size(); i++) {
    • If (i==3) list.remove(i);
    • }
  • Java introduced the Iterator class
    • Iterator it = list.iterator();
    • while(it.hasNext()) {Object o = it.next();}
    • for (; it.hasNext(); ) {Object o = it.next();}
  • Safe to modify structure
    • while(it.hasNext()) {
    • it.remove();
    • }