Computer Science 15-100, Fall 2008
Class Notes:  Interfaces


  1. Comparable (Natural Ordering)
    1. Comparable Example
    2. Comparable Methods
      1. compareTo
      2. Online Comparable API
  2. Comparator (Unnatural Ordering)
    1. Comparator Example
    2. Comparator Methods
      1. compare
      2. Online Comparator API
  3. ActionListener
    1. ActionListener Example
    2. ActionListener Methods
      1. actionPerformed
      2. Online ActionListener API
  4. Iterable and Iterator
    1. Iterable and Iterator Example
    2. Iterable<T> Methods
      1. iterator
      2. Online Iterable API
    3. Iterator<T> Methods
      1. hasNext
      2. next
      3. remove (optional)
      4. Online Iterator API
  5. Some Other Interesting Interfaces
    1. Serializable
    2. Runnable
    3. KeyListener
    4. MouseListener
    5. MouseMotionListener
    6. ComponentListener
    7. HyperlinkListener
    8. Scrollable
    9. List
    10. Many other JCF interfaces
  6. Writing Your Own Interface

Interfaces

  1. Comparable (Natural Ordering)
     
    1. Comparable Example

      Taken from earlier notes:
      "Sortable" == Implements Comparable Interface


      import java.util.*;
      class Demo {
        public static void main(String[] args) {
          // Declare, allocate, and load array with (somewhat) random pairs
          Random random = new Random();
          Pair[] pairs = new Pair[10];
          for (int i=0; i<pairs.length; i++)
            pairs[i] = new Pair(i%3, random.nextInt(10));

          // And print the unsorted values
          System.out.println(Arrays.toString(pairs));

          // Now sort them
          Arrays.sort(pairs);

          // And print the sorted values
          System.out.println(Arrays.toString(pairs));
        }
      }

      class Pair implements Comparable {
        private int x, y;
        public Pair(int x, int y) { this.x = x; this.y = y; }
        public String toString() {
          // abbreviated for this example
          return "(" + x + "," + y + ")";
        }

        // Must specify how to compare two Pair instances
        public int compareTo(Object object) {
          Pair that = (Pair) object;
          // Let's sort by x first, and in a tie, then by y
          if (this.x != that.x)
            return (this.x - that.x);
          else
           return (this.y - that.y);
        }
      }
       
    2. Comparable Methods
       
      1. compareTo
        public int compareTo(Object that); // Compares this object with that object,
                                           // returning a value <0 if this<that,
                                           // 0 if this equals that, and >0 if this>that.

         
      2. Online Comparable API
        1.4:  http://java.sun.com/j2se/1.4.2/docs/api/java/util/Comparable.html
        1.5 (with generics):  http://java.sun.com/j2se/1.5.0/docs/api/java/util/Comparable.html

         
  2. Comparator (Unnatural Ordering)
     
    1. Comparator Example
      import java.util.*;
      class Demo {
        public static void main(String[] args) {
          // Declare, allocate, and load array with (somewhat) random pairs
          Random random = new Random();
          Pair[] pairs = new Pair[10];
          for (int i=0; i<pairs.length; i++)
            pairs[i] = new Pair(i%3, random.nextInt(10));
      
          // And print the unsorted values
          System.out.println(Arrays.toString(pairs));
      
          // Now sort them
          Arrays.sort(pairs);
      
          // And print the naturally sorted values
          System.out.println("Natural ordering (using Comparable):");
          System.out.println(Arrays.toString(pairs));
      
          // Now re-sort them using the Comparator
          PairSorter pairSorter = new PairSorter();
          Arrays.sort(pairs, pairSorter); // sort with the given Comparator!
      
          // And print the unnaturally sorted values
          System.out.println("Unnatural ordering (using Comparator):");
          System.out.println(Arrays.toString(pairs));
        }
      }
      
      class PairSorter implements Comparator<Pair> {
        public int compare(Pair pair1, Pair pair2) {
          // We'll sort by the SUM of the pair's x + y
          int sum1 = pair1.getX() + pair1.getY();
          int sum2 = pair2.getX() + pair2.getY();
          return (sum1 - sum2);
        }
      }
      
      class Pair implements Comparable {
        private int x, y;
        public Pair(int x, int y) { this.x = x; this.y = y; }
        public String toString() {
          // abbreviated for this example
          return "(" + x + "," + y + ")";
        }
      
        public int getX() { return x; }
        public int getY() { return y; }
      
        // Must specify how to compare two Pair instances
        public int compareTo(Object object) {
          Pair that = (Pair) object;
          // Let's sort by x first, and in a tie, then by y
          if (this.x != that.x)
            return (this.x - that.x);
          else
           return (this.y - that.y);
        }
      }
    2. Comparator Methods
       
      1. compare
        public int compare(T obj1, T obj2);
                                           // Compares the two objects of type T,
                                           // returning a value <0 if obj1<obj2,
                                           // 0 if obj1 equals obj2, and >0 if obj1>obj2.

         
      2. Online Comparator API
        1.4:  http://java.sun.com/j2se/1.4.2/docs/api/java/util/Comparator.html
        1.5 (with generics):  http://java.sun.com/j2se/1.5.0/docs/api/java/util/Comparator.html

         
  3. ActionListener
     
    1. ActionListener Example

      Attempt #1: An ignored button!
      import java.awt.*;
      import javax.swing.*;
      class Demo {
        public static void main(String[] args) {
          JFrame frame = new JFrame("ActionListener Demo");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          JButton button = new JButton("Click to beep!");
          frame.getContentPane().add(button);
          frame.setSize(300,200);
          frame.setVisible(true);
        }
      }

      Attempt #2: A button that beeps:

      import java.awt.*;
      import javax.swing.*;
      import java.awt.event.*;
      class Demo {
        public static void main(String[] args) {
          JFrame frame = new JFrame("ActionListener Demo");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          JButton button = new JButton("Click to beep!");
          frame.getContentPane().add(button);
          frame.setSize(300,200);
          frame.setVisible(true);
      
          // Now make the button work
          ActionListener buttonListener = new ButtonListener();
          button.addActionListener(buttonListener);
        }
      }
      
      class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
          Toolkit.getDefaultToolkit().beep();
        }
      }

      Attempt #3: A button that beeps and counts the beeps!

      import java.awt.*;
      import javax.swing.*;
      import java.awt.event.*;
      class Demo {
        public static void main(String[] args) {
          JFrame frame = new JFrame("ActionListener Demo");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          JButton button = new JButton("Click to beep!");
          frame.getContentPane().add(button);
          frame.setSize(300,200);
          frame.setVisible(true);
      
          // Now make the button work
          ActionListener buttonListener = new ButtonListener(button);
          button.addActionListener(buttonListener);
        }
      }
      
      class ButtonListener implements ActionListener {
        private JButton button;
        private int beepCount;
      
        public ButtonListener(JButton button) {
          this.button = button;
          this.beepCount = 0;
        }
      
        public void actionPerformed(ActionEvent e) {
          Toolkit.getDefaultToolkit().beep();
          beepCount++;
          button.setText(beepCount + " beeps!  Click to beep again!");
        }
      }
    2. ActionListener Methods
       
      1. actionPerformed
        public void actionPerformed(ActionEvent e); // called when action occurs.
         
      2. Online ActionListener API
        http://java.sun.com/j2se/1.5.0/docs/api/java/awt/event/ActionListener.html
         
  4. Iterable and Iterator
     
    1. Iterable and Iterator Example

      What we want:
      class MyCode  {
        public static void main(String[] args) {
          String s = "Go Pens!";
          for (char c : s)  // will not compile (drats!)
            System.out.println(c);
        }
      }

      How we (sort of) get it:

      import java.util.*;
      class MyCode  {
        public static void main(String[] args) {
          IterableString s = new IterableString("Go Pens!");
          for (char c : s)
            System.out.println(c);
        }
      }
      
      class IterableString implements Iterable<Character> {
        private String stringValue;
      
        public IterableString(String stringValue) {
          this.stringValue = stringValue;
        }
      
        public String getStringValue() {
          return stringValue;
        }
      
        public Iterator<Character> iterator() {
          return new StringIterator(this);
        }
      }
      
      class StringIterator implements Iterator<Character> {
        private IterableString iterableString;
        private int nextIndex;
      
        public StringIterator(IterableString iterableString) {
          this.iterableString = iterableString;
          this.nextIndex = 0;
        }
      
        public boolean hasNext() {
          String stringValue = iterableString.getStringValue();
          return ((stringValue != null) &&
                  (nextIndex < stringValue.length()));
        }
      
        public Character next() {
          String stringValue = iterableString.getStringValue();
          return stringValue.charAt(nextIndex++);
        }
      
        public void remove() {
          // The "right" way to not support an optional method
          throw new UnsupportedOperationException();
        }
      }
    2. Iterable<T> Methods
       
      1. iterator
        public Iterator<T> iterator(); // returns an iterator over type T
         
      2. Online Iterable API
        1.4:  http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Iterable.html
        1.5 (with generics):  http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Iterable.html

         
    3. Iterator<T> Methods
       
      1. hasNext
        public boolean hasNext(); // returns true if the iterator has more elements
         
      2. next
        public T next(); // returns the next element (of type T) in the iteration
         
      3. remove (optional)
        public void remove(); // optional, so you do not have to implement this,
                              // though you must declare it in any case.

         
      4. Online Iterator API
        1.4:  http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Iterator.html
        1.5 (with generics):  http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Iterator.html

         
  5. Some Other Interesting Interfaces
    1. Serializable
    2. Runnable
    3. KeyListener
    4. MouseListener
    5. MouseMotionListener
    6. ComponentListener
    7. HyperlinkListener
    8. Scrollable
    9. List
    10. Many other JCF interfaces
       
  6. Writing Your Own Interface

carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem