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
Wednesday, August 4, 2010
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)
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.
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.
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
2) generics
3) threads, producer / consumer
4) rmi
5) sockets
6) exceptions
7) bubblesort
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();
}
}
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;
}
}
/**
* 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();
}
}
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();
}
}
Thursday, July 29, 2010
All about comparators
package mysorting;
import java.util.Comparator;
public class ComparePersonByName implements Comparator
{
@Override
public int compare(Object p1, Object p2) {
Person person1 = (Person)p1;
Person person2 = (Person)p2;
String s1 = person1.getName();
String s2 = person2.getName();
return s1.compareTo(s2);
}
}
package mysorting;
import java.util.Comparator;
public class ComparePersonByAge implements Comparator
{
@Override
public int compare(Object p1, Object p2) {
Person person1 = (Person)p1;
Person person2 = (Person)p2;
Integer age1 = person1.getAge();
Integer age2 = person2.getAge();
return age1.compareTo(age2);
}
}
package mysorting;
import java.util.Comparator;
import java.lang.reflect.*;
public class ComparePersonByNameDescending implements Comparator
{
@Override
public int compare(Object p1, Object p2) {
Person person1 = (Person)p1;
Person person2 = (Person)p2;
String s1 = person1.getName();
String s2 = person2.getName();
return - s1.compareTo(s2);
}
}
package mysorting;
public class Person implements Comparable
{
// fields
private String name; // the person's name
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private int maximumBooks;
// constructor
public Person(String n)
{
name = n;
maximumBooks = 3;
}
public Person(String n, int a)
{
name = n;
age = a;
maximumBooks = 3;
}
// getters and setters
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public int getMaximumBooks() {
return maximumBooks;
}
public void setMaximumBooks(int maxBooks) {
maximumBooks = maxBooks;
}
public String toString()
{
return getName() + " (" + getMaximumBooks() + " books)";
}
@Override
public int compareTo(Object arg0) {
Person p1 = (Person)arg0;
if (name.compareTo(p1.getName()) == 0 )
return 0;
else if (name.compareTo(p1.getName()) < 0)
return -1;
else if (name.compareTo(p1.getName()) > 0)
return +1;
return 0;
}
}
package mysorting;
import java.util.Comparator;
public class Sorting
{
public static void BubbleSort(Person a[], Comparator c)
{
for (int i = 0; i < a.length - 1; i++)
{
for (int j = 0; j < a.length - i - 1; j++)
{
if (c.compare(a[j], a[j+1]) > 0)
{
Person temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
} // end if
} // end for j
} // end for i
} // end method Bubblesort
public static void main(String args[])
{
Person a[] = new Person[4];
a[0] = new Person("mary", 12);
a[1] = new Person("jeremy", 10);
a[2] = new Person("susan", 15);
a[3] = new Person("josh", 20);
Sorting.BubbleSort(a, new ComparePersonByNameDescending());
for (Person x : a)
System.out.println(x);
System.out.println("");
Sorting.BubbleSort(a, new ComparePersonByAge());
for (Person x : a)
System.out.println(x);
}
}
import java.util.Comparator;
public class ComparePersonByName implements Comparator
{
@Override
public int compare(Object p1, Object p2) {
Person person1 = (Person)p1;
Person person2 = (Person)p2;
String s1 = person1.getName();
String s2 = person2.getName();
return s1.compareTo(s2);
}
}
package mysorting;
import java.util.Comparator;
public class ComparePersonByAge implements Comparator
{
@Override
public int compare(Object p1, Object p2) {
Person person1 = (Person)p1;
Person person2 = (Person)p2;
Integer age1 = person1.getAge();
Integer age2 = person2.getAge();
return age1.compareTo(age2);
}
}
package mysorting;
import java.util.Comparator;
import java.lang.reflect.*;
public class ComparePersonByNameDescending implements Comparator
{
@Override
public int compare(Object p1, Object p2) {
Person person1 = (Person)p1;
Person person2 = (Person)p2;
String s1 = person1.getName();
String s2 = person2.getName();
return - s1.compareTo(s2);
}
}
package mysorting;
public class Person implements Comparable
{
// fields
private String name; // the person's name
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private int maximumBooks;
// constructor
public Person(String n)
{
name = n;
maximumBooks = 3;
}
public Person(String n, int a)
{
name = n;
age = a;
maximumBooks = 3;
}
// getters and setters
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public int getMaximumBooks() {
return maximumBooks;
}
public void setMaximumBooks(int maxBooks) {
maximumBooks = maxBooks;
}
public String toString()
{
return getName() + " (" + getMaximumBooks() + " books)";
}
@Override
public int compareTo(Object arg0) {
Person p1 = (Person)arg0;
if (name.compareTo(p1.getName()) == 0 )
return 0;
else if (name.compareTo(p1.getName()) < 0)
return -1;
else if (name.compareTo(p1.getName()) > 0)
return +1;
return 0;
}
}
package mysorting;
import java.util.Comparator;
public class Sorting
{
public static void BubbleSort(Person a[], Comparator c)
{
for (int i = 0; i < a.length - 1; i++)
{
for (int j = 0; j < a.length - i - 1; j++)
{
if (c.compare(a[j], a[j+1]) > 0)
{
Person temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
} // end if
} // end for j
} // end for i
} // end method Bubblesort
public static void main(String args[])
{
Person a[] = new Person[4];
a[0] = new Person("mary", 12);
a[1] = new Person("jeremy", 10);
a[2] = new Person("susan", 15);
a[3] = new Person("josh", 20);
Sorting.BubbleSort(a, new ComparePersonByNameDescending());
for (Person x : a)
System.out.println(x);
System.out.println("");
Sorting.BubbleSort(a, new ComparePersonByAge());
for (Person x : a)
System.out.println(x);
}
}
how can you use delegates in Java, not using inner classes?
we can use Reflection:
http://www.javacamp.org/javavscsharp/delegate.html
we can use Reflection:
http://www.javacamp.org/javavscsharp/delegate.html
package mysorting;
public class Person implements Comparable
{
// fields
private String name; // the person's name
private int maximumBooks;
// constructor
public Person(String n)
{
name = n;
maximumBooks = 3;
}
// getters and setters
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public int getMaximumBooks() {
return maximumBooks;
}
public void setMaximumBooks(int maxBooks) {
maximumBooks = maxBooks;
}
public String toString()
{
return getName() + " (" + getMaximumBooks() + " books)";
}
@Override
public int compareTo(Object arg0) {
Person p1 = (Person)arg0;
if (name.compareTo(p1.getName()) == 0 )
return 0;
else if (name.compareTo(p1.getName()) < 0)
return -1;
else if (name.compareTo(p1.getName()) > 0)
return +1;
return 0;
}
}
public class Person implements Comparable
{
// fields
private String name; // the person's name
private int maximumBooks;
// constructor
public Person(String n)
{
name = n;
maximumBooks = 3;
}
// getters and setters
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public int getMaximumBooks() {
return maximumBooks;
}
public void setMaximumBooks(int maxBooks) {
maximumBooks = maxBooks;
}
public String toString()
{
return getName() + " (" + getMaximumBooks() + " books)";
}
@Override
public int compareTo(Object arg0) {
Person p1 = (Person)arg0;
if (name.compareTo(p1.getName()) == 0 )
return 0;
else if (name.compareTo(p1.getName()) < 0)
return -1;
else if (name.compareTo(p1.getName()) > 0)
return +1;
return 0;
}
}
package mysorting;
public class Sorting
{
public static void BubbleSort(Person 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)
{
Person temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
} // end if
} // end for j
} // end for i
} // end method Bubblesort
public static void main(String args[])
{
Person a[] = new Person[4];
a[0] = new Person("mary");
a[1] = new Person("jeremy");
a[2] = new Person("susan");
a[3] = new Person("josh");
Sorting.BubbleSort(a);
for (Person x : a)
System.out.println(x);
}
}
public class Sorting
{
public static void BubbleSort(Person 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)
{
Person temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
} // end if
} // end for j
} // end for i
} // end method Bubblesort
public static void main(String args[])
{
Person a[] = new Person[4];
a[0] = new Person("mary");
a[1] = new Person("jeremy");
a[2] = new Person("susan");
a[3] = new Person("josh");
Sorting.BubbleSort(a);
for (Person x : a)
System.out.println(x);
}
}
Tuesday, July 27, 2010
package mysorting;
public class Sorting
{
public static void BubbleSort(int a[])
{
for (int i = 0; i < a.length - 1; i++)
{
for (int j = 0; j < a.length - i - 1; j++)
{
if (a[j] > a[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
} // end if
} // end for j
} // end for i
} // end method Bubblesort
public static void main(String args[])
{
int a[] = new int [4];
a[0] = 5;
a[1] = 2;
a[2] = 9;
a[3] = 1;
Sorting.BubbleSort(a);
for (Integer x : a)
System.out.println(x);
}
}
public class Sorting
{
public static void BubbleSort(int a[])
{
for (int i = 0; i < a.length - 1; i++)
{
for (int j = 0; j < a.length - i - 1; j++)
{
if (a[j] > a[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
} // end if
} // end for j
} // end for i
} // end method Bubblesort
public static void main(String args[])
{
int a[] = new int [4];
a[0] = 5;
a[1] = 2;
a[2] = 9;
a[3] = 1;
Sorting.BubbleSort(a);
for (Integer x : a)
System.out.println(x);
}
}
Thursday, July 22, 2010
package myexceptions;
public class ExceptionExample1 {
public static void printf(String arg0) throws MyException
{
if (arg0 == null || arg0.length() < 5)
throw new MyException("string too short");
System.out.println(arg0);
}
public static void main(String[] args) throws MyException
{
printf("hi");
try
{
printf("hello world");
printf("hi");
if (true)
{
throw new MyException("silly error");
}
System.out.println("Hello");
}
catch (MyException e)
{
System.out.println(e.errmessage);
}
catch (IndexOutOfBoundsException e)
{
}
catch (Exception e)
{
}
System.out.println("And then we come here");
}
}
class MyException extends Exception
{
String errmessage;
public MyException(String errmess)
{
errmessage = errmess;
}
}
public class ExceptionExample1 {
public static void printf(String arg0) throws MyException
{
if (arg0 == null || arg0.length() < 5)
throw new MyException("string too short");
System.out.println(arg0);
}
public static void main(String[] args) throws MyException
{
printf("hi");
try
{
printf("hello world");
printf("hi");
if (true)
{
throw new MyException("silly error");
}
System.out.println("Hello");
}
catch (MyException e)
{
System.out.println(e.errmessage);
}
catch (IndexOutOfBoundsException e)
{
}
catch (Exception e)
{
}
System.out.println("And then we come here");
}
}
class MyException extends Exception
{
String errmessage;
public MyException(String errmess)
{
errmessage = errmess;
}
}
package rmiExample;
import java.rmi.Naming;
public class RmiServer {
/**
* Server program for the "Hello, world!" example.
* @param argv The command line arguments which are ignored.
*/
public static void main (String[] argv) {
try {
Naming.rebind ("Hello", new Hello ("Hello, world!"));
System.out.println ("Hello Server is ready.");
} catch (Exception e) {
System.out.println ("Hello Server failed: " + e);
}
}
}
import java.rmi.Naming;
public class RmiServer {
/**
* Server program for the "Hello, world!" example.
* @param argv The command line arguments which are ignored.
*/
public static void main (String[] argv) {
try {
Naming.rebind ("Hello", new Hello ("Hello, world!"));
System.out.println ("Hello Server is ready.");
} catch (Exception e) {
System.out.println ("Hello Server failed: " + e);
}
}
}
package rmiExample;
import java.rmi.Naming;
public class RmiClient {
/**
* Client program for the "Hello, world!" example.
* @param argv The command line arguments which are ignored.
*/
public static void main (String[] argv) {
try {
HelloInterface hello =
(HelloInterface) Naming.lookup ("//ortles.ccs.neu.edu/Hello");
System.out.println (hello.say());
} catch (Exception e) {
System.out.println ("HelloClient exception: " + e);
}
}
}
import java.rmi.Naming;
public class RmiClient {
/**
* Client program for the "Hello, world!" example.
* @param argv The command line arguments which are ignored.
*/
public static void main (String[] argv) {
try {
HelloInterface hello =
(HelloInterface) Naming.lookup ("//ortles.ccs.neu.edu/Hello");
System.out.println (hello.say());
} catch (Exception e) {
System.out.println ("HelloClient exception: " + e);
}
}
}
package rmiExample;
import java.rmi.*;
import java.rmi.server.*;
/**
* Remote Class for the "Hello, world!" example.
*/
public class Hello extends UnicastRemoteObject implements HelloInterface {
private String message;
/**
* Construct a remote object
* @param msg the message of the remote object, such as "Hello, world!".
* @exception RemoteException if the object handle cannot be constructed.
*/
public Hello (String msg) throws RemoteException {
message = msg;
}
/**
* Implementation of the remotely invokable method.
* @return the message of the remote object, such as "Hello, world!".
* @exception RemoteException if the remote invocation fails.
*/
public String say() throws RemoteException {
return message;
}
}
import java.rmi.*;
import java.rmi.server.*;
/**
* Remote Class for the "Hello, world!" example.
*/
public class Hello extends UnicastRemoteObject implements HelloInterface {
private String message;
/**
* Construct a remote object
* @param msg the message of the remote object, such as "Hello, world!".
* @exception RemoteException if the object handle cannot be constructed.
*/
public Hello (String msg) throws RemoteException {
message = msg;
}
/**
* Implementation of the remotely invokable method.
* @return the message of the remote object, such as "Hello, world!".
* @exception RemoteException if the remote invocation fails.
*/
public String say() throws RemoteException {
return message;
}
}
package rmiExample;
import java.rmi.*;
import java.rmi.server.*;
/**
* Remote Class for the "Hello, world!" example.
*/
public class Hello extends UnicastRemoteObject implements HelloInterface {
private String message;
/**
* Construct a remote object
* @param msg the message of the remote object, such as "Hello, world!".
* @exception RemoteException if the object handle cannot be constructed.
*/
public Hello (String msg) throws RemoteException {
message = msg;
}
/**
* Implementation of the remotely invokable method.
* @return the message of the remote object, such as "Hello, world!".
* @exception RemoteException if the remote invocation fails.
*/
public String say() throws RemoteException {
return message;
}
}
import java.rmi.*;
import java.rmi.server.*;
/**
* Remote Class for the "Hello, world!" example.
*/
public class Hello extends UnicastRemoteObject implements HelloInterface {
private String message;
/**
* Construct a remote object
* @param msg the message of the remote object, such as "Hello, world!".
* @exception RemoteException if the object handle cannot be constructed.
*/
public Hello (String msg) throws RemoteException {
message = msg;
}
/**
* Implementation of the remotely invokable method.
* @return the message of the remote object, such as "Hello, world!".
* @exception RemoteException if the remote invocation fails.
*/
public String say() throws RemoteException {
return message;
}
}
package rmiExample;
import java.rmi.*;
/**
* Remote Interface for the "Hello, world!" example.
*/
public interface HelloInterface extends Remote {
/**
* Remotely invocable method.
* @return the message of the remote object, such as "Hello, world!".
* @exception RemoteException if the remote invocation fails.
*/
public String say() throws RemoteException;
}
import java.rmi.*;
/**
* Remote Interface for the "Hello, world!" example.
*/
public interface HelloInterface extends Remote {
/**
* Remotely invocable method.
* @return the message of the remote object, such as "Hello, world!".
* @exception RemoteException if the remote invocation fails.
*/
public String say() throws RemoteException;
}
package mylinkedlist;
import java.util.Collection;
import java.util.Iterator;
public class LinkedList<T> implements java.util.Collection<T>
{
LLNode<T> head;
LLNode<T> tail;
int count;
LinkedList()
{
head = tail = null;
count = 0;
}
public Iterator<T> iterator()
{
return new LLIterator(this);
}
void addAtBeginning(T n)
{
count++;
LLNode<T> ln = new LLNode<T>(n);
if (isEmpty())
{
head = ln;
tail = ln;
}
else
{
ln.next = head;
head = ln;
}
}
public boolean isEmpty()
{
return head == null;
}
void printAllItems()
{
for (LLNode<T> i = head; i != null; i = i.next)
System.out.println(i.value);
}
T front()
{
if (head == null)
return null;
else
return head.value;
}
T rear()
{
LLNode<T> prev = null;
for (LLNode<T> i = head; i != null; i = i.next)
prev = i;
if (prev == null)
return null;
else
return prev.value;
}
public int size()
{
// int count = 0;
// for (LLNode i = head; i != null; i = i.next)
// count++;
return count;
}
void addAtEnd(T n)
{
// LLNode prev = null;
// for (LLNode i = head; i != null; i = i.next)
// prev = i;
//
// if (prev == null)
// ;
// else
// {
// prev.next = new LLNode(n);
// count++;
// }
count++;
LLNode ln = new LLNode<T>(n);
if (isEmpty())
{
head = ln;
tail = ln;
}
else
{
tail.next = ln;
tail = ln;
}
}
@Override
public boolean add(Object arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean addAll(Collection arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public void clear() {
head = tail = null;
count = 0;
}
@Override
public boolean contains(Object arg0) {
for (T x : this)
if (x == arg0)
return true;
return false;
}
@Override
public boolean containsAll(Collection c)
{
for (Object x : c)
if (contains(x) == false)
return false;
return true;
}
@Override
public boolean remove(Object arg0) {
if (count == 1 && head.value == arg0)
{
head = tail = null;
count--;
return true;
}
LLNode<T> prev;
for(prev = head; prev != null && prev.next.value != arg0; prev = prev.next)
{ // do nothing
}
if (prev == null || prev.next.value != arg0)
return false;
else
{
prev.next = prev.next.next;
count--;
return true;
}
// we didn't handle where it is the first item
}
@Override
public boolean removeAll(Collection c) {
for (Object x : c)
remove(x);
return true;
}
@Override
public boolean retainAll(Collection arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public Object[] toArray() {
Object [] retval = new Object[count];
int i = 0;
for (T x : this)
{
retval[i] = x;
i++;
}
return null;
}
@Override
public Object[] toArray(Object[] arg0) {
// TODO Auto-generated method stub
return null;
}
}
//void swap(LL a, LL b)
//{
// LL t = new LL();
// t.head = a.head;
// t.tail = a.tail;
// t.count = a.count;
//
// a.head = b.head;
// a.tail = b.tail;
// a.count = b.count;
//
// b.head = t.head;
// b.tail = t.tail;
// b.count = t.count;
//}
//
//System.out.println(s == t);
import java.util.Collection;
import java.util.Iterator;
public class LinkedList<T> implements java.util.Collection<T>
{
LLNode<T> head;
LLNode<T> tail;
int count;
LinkedList()
{
head = tail = null;
count = 0;
}
public Iterator<T> iterator()
{
return new LLIterator(this);
}
void addAtBeginning(T n)
{
count++;
LLNode<T> ln = new LLNode<T>(n);
if (isEmpty())
{
head = ln;
tail = ln;
}
else
{
ln.next = head;
head = ln;
}
}
public boolean isEmpty()
{
return head == null;
}
void printAllItems()
{
for (LLNode<T> i = head; i != null; i = i.next)
System.out.println(i.value);
}
T front()
{
if (head == null)
return null;
else
return head.value;
}
T rear()
{
LLNode<T> prev = null;
for (LLNode<T> i = head; i != null; i = i.next)
prev = i;
if (prev == null)
return null;
else
return prev.value;
}
public int size()
{
// int count = 0;
// for (LLNode i = head; i != null; i = i.next)
// count++;
return count;
}
void addAtEnd(T n)
{
// LLNode prev = null;
// for (LLNode i = head; i != null; i = i.next)
// prev = i;
//
// if (prev == null)
// ;
// else
// {
// prev.next = new LLNode(n);
// count++;
// }
count++;
LLNode ln = new LLNode<T>(n);
if (isEmpty())
{
head = ln;
tail = ln;
}
else
{
tail.next = ln;
tail = ln;
}
}
@Override
public boolean add(Object arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean addAll(Collection arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public void clear() {
head = tail = null;
count = 0;
}
@Override
public boolean contains(Object arg0) {
for (T x : this)
if (x == arg0)
return true;
return false;
}
@Override
public boolean containsAll(Collection c)
{
for (Object x : c)
if (contains(x) == false)
return false;
return true;
}
@Override
public boolean remove(Object arg0) {
if (count == 1 && head.value == arg0)
{
head = tail = null;
count--;
return true;
}
LLNode<T> prev;
for(prev = head; prev != null && prev.next.value != arg0; prev = prev.next)
{ // do nothing
}
if (prev == null || prev.next.value != arg0)
return false;
else
{
prev.next = prev.next.next;
count--;
return true;
}
// we didn't handle where it is the first item
}
@Override
public boolean removeAll(Collection c) {
for (Object x : c)
remove(x);
return true;
}
@Override
public boolean retainAll(Collection arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public Object[] toArray() {
Object [] retval = new Object[count];
int i = 0;
for (T x : this)
{
retval[i] = x;
i++;
}
return null;
}
@Override
public Object[] toArray(Object[] arg0) {
// TODO Auto-generated method stub
return null;
}
}
//void swap(LL a, LL b)
//{
// LL t = new LL();
// t.head = a.head;
// t.tail = a.tail;
// t.count = a.count;
//
// a.head = b.head;
// a.tail = b.tail;
// a.count = b.count;
//
// b.head = t.head;
// b.tail = t.tail;
// b.count = t.count;
//}
//
//System.out.println(s == t);
Thursday, July 15, 2010
package org.cs212.hello;
public class RoadBike extends Bicycle{
private int tireWidth; // In millimeters (mm)
public RoadBike(int startCadence, int startSpeed, int startGear, int newTireWidth){
super(startCadence, startSpeed, startGear);
this.setTireWidth(newTireWidth);
}
public int getTireWidth(){
return this.tireWidth;
}
public void setTireWidth(int newTireWidth){
this.tireWidth = newTireWidth;
}
public void printDescription(){
super.printDescription();
System.out.println("The RoadBike has " + getTireWidth()
+ " MM tires.");
}
}
public class RoadBike extends Bicycle{
private int tireWidth; // In millimeters (mm)
public RoadBike(int startCadence, int startSpeed, int startGear, int newTireWidth){
super(startCadence, startSpeed, startGear);
this.setTireWidth(newTireWidth);
}
public int getTireWidth(){
return this.tireWidth;
}
public void setTireWidth(int newTireWidth){
this.tireWidth = newTireWidth;
}
public void printDescription(){
super.printDescription();
System.out.println("The RoadBike has " + getTireWidth()
+ " MM tires.");
}
}
package org.cs212.hello;
public class MountainBike extends Bicycle{
private String suspension;
public double name;
public MountainBike(int startCadence, int startSpeed, int startGear, String suspensionType){
super(startCadence, startSpeed, startGear);
this.setSuspension(suspensionType);
}
public String getSuspension(){
return this.suspension;
}
public void setSuspension(String suspensionType){
this.suspension = suspensionType;
}
public void printDescription(){
super.printDescription();
System.out.println("The MountainBike has a " + getSuspension()
+ " suspension.");
}
}
public class MountainBike extends Bicycle{
private String suspension;
public double name;
public MountainBike(int startCadence, int startSpeed, int startGear, String suspensionType){
super(startCadence, startSpeed, startGear);
this.setSuspension(suspensionType);
}
public String getSuspension(){
return this.suspension;
}
public void setSuspension(String suspensionType){
this.suspension = suspensionType;
}
public void printDescription(){
super.printDescription();
System.out.println("The MountainBike has a " + getSuspension()
+ " suspension.");
}
}
package org.cs212.hello;
public class Bicycle {
// the Bicycle class has three fields
public int cadence;
public int gear;
public int speed;
public int name;
// the Bicycle class has one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
// the Bicycle class has four methods
public void setCadence(int newValue) {
cadence = newValue;
}
public void printDescription()
{
System.out.println("\nBike is in gear " + this.gear + " with a cadence of " +
this.cadence + " and travelling at a speed of " + this.speed + ". ");
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
}
public class Bicycle {
// the Bicycle class has three fields
public int cadence;
public int gear;
public int speed;
public int name;
// the Bicycle class has one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
// the Bicycle class has four methods
public void setCadence(int newValue) {
cadence = newValue;
}
public void printDescription()
{
System.out.println("\nBike is in gear " + this.gear + " with a cadence of " +
this.cadence + " and travelling at a speed of " + this.speed + ". ");
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
}
package org.cs212.hello;
import java.util.ArrayList;
public class MyLibrary {
ArrayList<Book> books;
ArrayList<Person> people;
String name;
public MyLibrary(String n)
{
name = n;
books = new ArrayList<Book>();
people = new ArrayList<Person>();
}
public ArrayList<Book> getBooks() {
return books;
}
public ArrayList<Person> getPeople() {
return people;
}
public String getName() {
return name;
}
public void addBook(Book b)
{
books.add(b);
}
public void addPerson(Person p)
{
people.add(p);
}
public void removePerson(Person p)
{
people.remove(p);
}
public void removeBook(Book b)
{
books.remove(b);
}
boolean checkOut(Book b, Person p)
{
if (b.getPerson() == null &&
getBooksForPerson(p).size() == p.getMaximumBooks())
{
b.setPerson(p);
return true;
}
else
{
return false;
}
}
boolean checkIn(Book b)
{
if (b.getPerson() != null)
{
b.setPerson(null);
return true;
}
else
{
return false;
}
}
ArrayList<Book> getBooksForPerson(Person p)
{
ArrayList<Book> result = new ArrayList<Book>();
for (Book x : books)
{
if (x.getPerson() != null &&
x.getPerson().getName().equals(p.getName())
)
result.add(x);
}
return result;
}
}
import java.util.ArrayList;
public class MyLibrary {
ArrayList<Book> books;
ArrayList<Person> people;
String name;
public MyLibrary(String n)
{
name = n;
books = new ArrayList<Book>();
people = new ArrayList<Person>();
}
public ArrayList<Book> getBooks() {
return books;
}
public ArrayList<Person> getPeople() {
return people;
}
public String getName() {
return name;
}
public void addBook(Book b)
{
books.add(b);
}
public void addPerson(Person p)
{
people.add(p);
}
public void removePerson(Person p)
{
people.remove(p);
}
public void removeBook(Book b)
{
books.remove(b);
}
boolean checkOut(Book b, Person p)
{
if (b.getPerson() == null &&
getBooksForPerson(p).size() == p.getMaximumBooks())
{
b.setPerson(p);
return true;
}
else
{
return false;
}
}
boolean checkIn(Book b)
{
if (b.getPerson() != null)
{
b.setPerson(null);
return true;
}
else
{
return false;
}
}
ArrayList<Book> getBooksForPerson(Person p)
{
ArrayList<Book> result = new ArrayList<Book>();
for (Book x : books)
{
if (x.getPerson() != null &&
x.getPerson().getName().equals(p.getName())
)
result.add(x);
}
return result;
}
}
package org.cs212.hello;
public class Person
{
// fields
private String name; // the person's name
private int maximumBooks;
// constructor
public Person()
{
name = "unknown name";
maximumBooks = 3;
}
// getters and setters
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public int getMaximumBooks() {
return maximumBooks;
}
public void setMaximumBooks(int maxBooks) {
maximumBooks = maxBooks;
}
public String toString()
{
return getName() + " (" + getMaximumBooks() + " books)";
}
}
public class Person
{
// fields
private String name; // the person's name
private int maximumBooks;
// constructor
public Person()
{
name = "unknown name";
maximumBooks = 3;
}
// getters and setters
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public int getMaximumBooks() {
return maximumBooks;
}
public void setMaximumBooks(int maxBooks) {
maximumBooks = maxBooks;
}
public String toString()
{
return getName() + " (" + getMaximumBooks() + " books)";
}
}
package org.cs212.hello;
public class Book {
String title;
String author;
Person person;
public Book(String string) {
this.title = string;
this.author = "unknown author";
}
public void setPerson(Person p) {
person = p;
}
public Person getPerson() {
return person;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
}
public class Book {
String title;
String author;
Person person;
public Book(String string) {
this.title = string;
this.author = "unknown author";
}
public void setPerson(Person p) {
person = p;
}
public Person getPerson() {
return person;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
}
package mylinkedlist;
public class MyMain {
/**
* @param args
*/
public static void main(String[] args) {
LinkedList<Integer> myLL = new LinkedList<Integer>();
System.out.println(myLL.isEmpty());
if (! myLL.isEmpty())
System.out.println(myLL.front());
myLL.addAtBeginning(5);
myLL.addAtBeginning(6);
myLL.addAtBeginning(15);
myLL.printAllItems();
System.out.println(myLL.front());
}
}
public class MyMain {
/**
* @param args
*/
public static void main(String[] args) {
LinkedList<Integer> myLL = new LinkedList<Integer>();
System.out.println(myLL.isEmpty());
if (! myLL.isEmpty())
System.out.println(myLL.front());
myLL.addAtBeginning(5);
myLL.addAtBeginning(6);
myLL.addAtBeginning(15);
myLL.printAllItems();
System.out.println(myLL.front());
}
}
package mylinkedlist;
public class LinkedList<T>
{
LLNode<T> head;
LLNode tail;
int count;
LinkedList()
{
head = tail = null;
count = 0;
}
void addAtBeginning(T n)
{
count++;
LLNode<T> ln = new LLNode<T>(n);
if (isEmpty())
{
head = ln;
tail = ln;
}
else
{
ln.next = head;
head = ln;
}
}
boolean isEmpty()
{
return head == null;
}
void printAllItems()
{
for (LLNode<T> i = head; i != null; i = i.next)
System.out.println(i.value);
}
T front()
{
if (head == null)
return null;
else
return head.value;
}
T rear()
{
LLNode<T> prev = null;
for (LLNode<T> i = head; i != null; i = i.next)
prev = i;
if (prev == null)
return null;
else
return prev.value;
}
int size()
{
// int count = 0;
// for (LLNode i = head; i != null; i = i.next)
// count++;
return count;
}
void addAtEnd(T n)
{
// LLNode prev = null;
// for (LLNode i = head; i != null; i = i.next)
// prev = i;
//
// if (prev == null)
// ;
// else
// {
// prev.next = new LLNode(n);
// count++;
// }
count++;
LLNode ln = new LLNode<T>(n);
if (isEmpty())
{
head = ln;
tail = ln;
}
else
{
tail.next = ln;
tail = ln;
}
}
}
public class LinkedList<T>
{
LLNode<T> head;
LLNode tail;
int count;
LinkedList()
{
head = tail = null;
count = 0;
}
void addAtBeginning(T n)
{
count++;
LLNode<T> ln = new LLNode<T>(n);
if (isEmpty())
{
head = ln;
tail = ln;
}
else
{
ln.next = head;
head = ln;
}
}
boolean isEmpty()
{
return head == null;
}
void printAllItems()
{
for (LLNode<T> i = head; i != null; i = i.next)
System.out.println(i.value);
}
T front()
{
if (head == null)
return null;
else
return head.value;
}
T rear()
{
LLNode<T> prev = null;
for (LLNode<T> i = head; i != null; i = i.next)
prev = i;
if (prev == null)
return null;
else
return prev.value;
}
int size()
{
// int count = 0;
// for (LLNode i = head; i != null; i = i.next)
// count++;
return count;
}
void addAtEnd(T n)
{
// LLNode prev = null;
// for (LLNode i = head; i != null; i = i.next)
// prev = i;
//
// if (prev == null)
// ;
// else
// {
// prev.next = new LLNode(n);
// count++;
// }
count++;
LLNode ln = new LLNode<T>(n);
if (isEmpty())
{
head = ln;
tail = ln;
}
else
{
tail.next = ln;
tail = ln;
}
}
}
Material:
Java syntax:
primatives vs. reference types
strings, string comparison, assignment
Integer vs. integer
pass by reference vs. by value
classes, objects
arrays vs. arraylists
arraylists vs arraylists
static vs. non-static data members and methods
public, private, protected, package
inheritance via extends
implements for interfaces
semantics:
Person, Book, MyLibrary class and how they interact
Linked list
Maybe to make a similar class, extend the class by adding functionality
Java syntax:
primatives vs. reference types
strings, string comparison, assignment
Integer vs. integer
pass by reference vs. by value
classes, objects
arrays vs. arraylists
arraylists vs arraylists
static vs. non-static data members and methods
public, private, protected, package
inheritance via extends
implements for interfaces
semantics:
Person, Book, MyLibrary class and how they interact
Linked list
Maybe to make a similar class, extend the class by adding functionality
Monday, July 12, 2010
Thursday, July 8, 2010
Plan:
1) arrays, how to use, limitations
2) ArrayLists (both of Object and generics)
3) Inheritance
class Person
{
static String firstname;
String lastname;
String ssn;
int age;
static void takeAWalk() { ... }
}
class Customer extends Person
{
}
class Employee extends Person
{
takeAWalk() { ... }
}
main()
{
Person x;
Person.firstName;
x.firstName;
x.takeAWalk();
}
4) if there is time, some more Applet material
1) arrays, how to use, limitations
2) ArrayLists (both of Object and generics)
3) Inheritance
class Person
{
static String firstname;
String lastname;
String ssn;
int age;
static void takeAWalk() { ... }
}
class Customer extends Person
{
}
class Employee extends Person
{
takeAWalk() { ... }
}
main()
{
Person x;
Person.firstName;
x.firstName;
x.takeAWalk();
}
4) if there is time, some more Applet material
Wednesday, June 30, 2010
package org.cs212.hello;
public class Hello {
public static void main(String[] args) {
int a = 5;
int b = 5;
if (a==b)
System.out.println("a equals b");
Integer A = new Integer(5);
Integer B = new Integer(5);
if (A.equals(b))
System.out.println("A equals B");
/*
String s = "Goodbye";
System.out.println(s);
String t = "Good";
t = t + "bye";
System.out.println(t);
System.out.println(s == t);
if (s.equals(t))
{
System.out.println("They are equal!");
}
System.out.println("hello");
Person p = new Person();
p.setName("Fred");
System.out.println(p.getName());
Person q; // = new Person();
//q.setName("Fred");
q = p;
if(p==q)
{
System.out.println("same");
}
else
{
System.out.println("different");
}*/
}
}
public class Hello {
public static void main(String[] args) {
int a = 5;
int b = 5;
if (a==b)
System.out.println("a equals b");
Integer A = new Integer(5);
Integer B = new Integer(5);
if (A.equals(b))
System.out.println("A equals B");
/*
String s = "Goodbye";
System.out.println(s);
String t = "Good";
t = t + "bye";
System.out.println(t);
System.out.println(s == t);
if (s.equals(t))
{
System.out.println("They are equal!");
}
System.out.println("hello");
Person p = new Person();
p.setName("Fred");
System.out.println(p.getName());
Person q; // = new Person();
//q.setName("Fred");
q = p;
if(p==q)
{
System.out.println("same");
}
else
{
System.out.println("different");
}*/
}
}
public class Person
{
// fields
private String name; // the person's name
private int maximumBooks;
// constructor
public Person()
{
name = "unknown name";
maximumBooks = 3;
}
qccs212.blogspot.com
// getters and setters
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public int getMaximumBooks() {
return maximumBooks;
}
public void setMaximumBooks(int maxBooks) {
maximumBooks = maxBooks;
}
}
{
// fields
private String name; // the person's name
private int maximumBooks;
// constructor
public Person()
{
name = "unknown name";
maximumBooks = 3;
}
qccs212.blogspot.com
// getters and setters
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public int getMaximumBooks() {
return maximumBooks;
}
public void setMaximumBooks(int maxBooks) {
maximumBooks = maxBooks;
}
}
Subscribe to:
Posts (Atom)