Wednesday, August 4, 2010

I need to submit grades by: Aug 11
Try to get projects to me by Aug 10th, or else
let me know that it is coming.

more material for final:
implementing interfaces of:
Collection
Iterable
Iterator
Comparable
Comparator
know at least two design patterns

Tuesday, August 3, 2010

Java midterm 2

1) Using generics, inheritance and polymorphism -- make a base class and two derived classes representing real world objects. (My example, which you should not take, is Bicycle as base class, and MountainBike and RoadBike as derived classes.) The base class should have some meaningful method, e.g. rideForward, which moves the respective Bicycle forward. (But again, come up with your own.) Each of the derived classes should overload that method (and mark it with the appropriate @ marker to note that you are overriding it). Create a linked list, or array, or collection of some sort, which can contain elements which are either the base class or a derived class. Iterate through the collection, and call the method. Assuming you did this correctly, and the polymorphism works, the appropriate method should be called.

2) Create an Exception class of your own which inherits from Exception. Write code that uses it. Function foo should throw it, function bar (which called foo) should catch it and print an error message.

3) Here is some code for templatized BubbleSort. Why can't we just use the > symbol? (5 pts) Write a class called MotorBike, which we can sort in ascending order by topSpeed (a public data member). (5 pts) Create an array and call the appropriate method to cause it to be sorted. (10 pts)


public class Sorting <T>
{
    public static void BubbleSort(T a[])
    {
        for (int i = 0; i < a.length - 1; i++)
            for (int j = 0; j < a.length - i - 1; j++)
                if (a[j].compareTo(a[j+1]) > 0)
                {
                    T temp = a[j];
                    a[j] = a[j+1];
                    a[j+1] = temp;
                } // end if
    } // end method Bubblesort




4) Trace through this Producer / Consumer code, giving the output, assuming we have two producers and two consumers. At each point, keep track of all variables of each object.


public class Producer extends Thread {
    private CubbyHole cubbyhole;
    private int number;

    public Producer(CubbyHole c, int number) {
        cubbyhole = c;
        this.number = number;
    }

    public void run() {
        for (int i = 0; i < 3; i++) {
            cubbyhole.put(i);
            System.out.println("Producer #" + this.number
                               + " put: " + i);
            try {
                sleep((int)(Math.random() * 100));
            } catch (InterruptedException e) { }
        }
    }



public class Consumer extends Thread {
    private CubbyHole cubbyhole;
    private int number;

    public Consumer(CubbyHole c, int number) {
        cubbyhole = c;
        this.number = number;
    }

    public void run() {
        int value = 0;
        for (int i = 0; i < 3; i++) {
            value = cubbyhole.get();
            System.out.println("Consumer #" + this.number
                               + " got: " + value);
        }
    }
}

public class CubbyHole {
    private int contents;
    private boolean available = false;

    public synchronized int get() {
        while (available == false) {
            try {
                wait();
            } catch (InterruptedException e) { }
        }
        available = false;
        notifyAll();
        return contents;
    }

    public synchronized void put(int value) {
        while (available == true) {
            try {
                wait();
            } catch (InterruptedException e) { }
        }
        contents = value;
        available = true;
        notifyAll();
    }
}


public class ProducerConsumerTest {
    public static void main(String[] args) {
        CubbyHole c = new CubbyHole();
        Producer p1 = new Producer(c, 1);


Producer p2 = new Producer(c, 2);
Consumer c1 = new Consumer(c, 1);


Consumer c2 = new Consumer(c, 2);
p1.start(); c1.start();


p2.start();
        c2.start();
} }

5) Describe, in words, the setup of RMI. What interfaces do we need, what classes do we need, and so on; and why do we need each. How do they work together? Maybe draw a diagram. Alternatively: the same thing for Sockets, instead of for RMI.

Monday, August 2, 2010

Study Guide for Optional second midterm

1) inheritance
2) generics
3) threads, producer / consumer
4) rmi
5) sockets
6) exceptions
7) bubblesort
Tutorial from Sun on Sockets
package innerclasspackage;
import java.util.LinkedList;
public class MyStack
{
    private LinkedList myLL = new LinkedList();
    MyStack()
    {
       
    }
    void push(int n)
    {
        myLL.addFirst(n);
    }
    void pop()
    {
        myLL.removeFirst();
    }
    int top()
    {
        return (Integer)myLL.get(0);
    }
    boolean isEmpty()
    {
        return myLL.isEmpty();
    }
}
package innerclasspackage;

/**
 * A utility class of which at most one instance
 * can exist per VM.
 *
 * Use Singleton.instance() to access this
 * instance.
 */
public class Singleton {
   /**
    * The constructor could be made private
    * to prevent others from instantiating this class.
    * But this would also make it impossible to
    * create instances of Singleton subclasses.
    */
   protected Singleton() {
     // ...
   }


   /**
    * A handle to the unique Singleton instance.
    */
   static private Singleton _instance = null;

   /**
    * @return The unique instance of this class.
    */
   static public Singleton instance() {
      if(null == _instance) {
         _instance = new Singleton();
      }
      return _instance;
   }



}
package innerclasspackage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class Person
{
    String name = "Josh";
    void foo()
    {
        Print p = new toFile();
        Print q = new toConsole();
        Display(p);
        Display(q);
    }
   
    private void Display(Print p) {
        p.invoke();
    }

    interface Print {
        void invoke();
    }
   
    class toFile implements Print
    {
        @Override
        public void invoke() {
            File f = new File("c:/josh/delegate.txt");
            try{
                PrintWriter fileOut =
                   new PrintWriter(new FileOutputStream(f));
                fileOut.write(name);
                fileOut.flush();
                fileOut.close();
            }catch(IOException ioe) {}   
        }
       
    }
   
    class toConsole implements Print
    {
        @Override
        public void invoke() {
            System.out.print(name+" ");
           
        }
       
    }
   
    public static void main(String[] args)
    {
        Person p = new Person();
        p.foo();
    }

}