Generic class definitions and one implementation
Type parameterization goes in the horizontal direction while abstraction takes care of the
vertical direction. The idea is the same, reusability and other OOP goodness.
“The Class, the central notion in Object Technology, can be viewed as the product of the
corporate merger between the module and type concepts.”
A generic class declared as C[G] is, rather than a type, a type pattern covering an infinite
set of possible types; you can obtain any one of these by providing an actual generic
parameter – itself a type - corresponding to G.
Java allows the use of wildcards to specify bounds on what type of parameters a given
generic object may have. E.g. List indicates a list which has an unknown object
type.
List is pronounced as List of Unknowns.
Void printCollection (Collection c) {
For (Object e : c)
System.out.println(e);
} // will work for any collection of objects.
//But if the formal argument is Collection then, it will not!
This is because, in general, if Parrot is a subtype (subclasss or subinterface) of
Bar, and G is some Generic type declaration, it is not the case that G is a
subtype of G.
To specify the upper bound of a generic element, the extends keyword is used, which
indicates that the generic type is a subclass (either extends the class, or
implements the interface) of the bounding class.
So List means that the given list contains objects which extend the
Shape class; for example, the list could be List or List.
To specify the lower bound of a generic element, the super keyword is used, which
indicates that the generic type is a superclass of the bounding class.
So, List could be List or List or List.
Example Implementation: The fictitious “formal generic parameter” here is E.
public class OopList {
protected class Node{
E element;
Node next;
Node (E e, Node n){ element = e; next = n; }
}
protected Node _head;
/** Construct the empty List. */
public OopList() { _head = null; }
/** Add item to the beginning of the List. */
public void add (E element) {
_head = new Node (element, _head);
}
/** Return true iff this List is empty. */
public boolean isEmpty() { return _head == null; }
public String toString() {
String x = "( ";
while (!isEmpty()){
x = x + this._head.element + " ";
_head = _head.next;
}
return x + ")";
}
/** Allow iteration. */
public java.util.Iterator elements() {
return new OopListIterator (this);
}
public static void main (String [] args) {
OopList OopLT = new OopList ();
OopLT.add("Hello");
OopLT.add("Not");
OopLT.add("Done");
System.out.println(OopLT.toString());
}
} // End of class
//********************************************************
// beginning of Iterator class. OopListIterator.
import java.util.*;
public class OopListIterator implements Iterator {
private OopList _list;
private OopList.Node _current;
public OopListIterator (OopList list){
_list = list;
_current = _list._head;
}
public boolean hasNext () { return (_current != null); }
public E next() throws NoSuchElementException {
if (_current == null)
throw new NoSuchElementException();
E result = _current.element;
_current = _current.next;
return (result);
}
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
}
//************************************************ Test Classes
public class Animal {
protected String x;
protected int age;
protected boolean pet;
public Animal (String y, int v, boolean i){
x = y;
age = v;
pet = i;
}
public String toString (){
String voila = "";
voila = "Name: " + x + " " + "Age: " + age + " "+ " Pet: " + pet;
return voila;
}
public static void main (String [] args){
Animal me = new Animal ("Tiger", 33, true);
System.out.println("Tiger is: ");
System.out.println(me.toString());
Animal Parrot1 = new Parrot ("P", 3, true);
System.out.println("Parrot is: ");
System.out.println(Parrot1.toString());
}
}
//*****************************************
public class Parrot extends Animal {
public Parrot (String x, int v, boolean z){
super(x, v, z);
this.x = "Parrot";
}
}
// JUNIT Testing:
//********************************************************
import junit.framework.TestCase;
public class OopListTest extends TestCase {
public void OopListConstructorTest() {
OopList OopLT = new OopList ();
assertTrue (OopLT.isEmpty());
}
public void testOopList() {
OopList OopLT = new OopList ();
assertTrue (OopLT.isEmpty());
}
public void testAdd() {
OopList OopLT = new OopList ();
OopLT.add("Hello");
OopLT.add("Not");
OopLT.add("Done");
assertEquals ("( Done Not Hello )", OopLT.toString());
}
public void testIsEmpty() {
OopList OopLT = new OopList ();
assertTrue (OopLT.isEmpty());
}
public void testElements() {
OopList OopLT = new OopList ();
OopListIterator iter1 = new OopListIterator (OopLT);
assertFalse (iter1.hasNext());
OopLT.add("Hello");
OopLT.add("Not");
OopLT.add("Done");
OopListIterator iter = new OopListIterator (OopLT);
assertFalse (OopLT.isEmpty());
assertTrue (iter.hasNext());
assertTrue (iter.hasNext());
assertEquals("Done", iter.next().toString());
assertEquals("Not", iter.next().toString());
assertEquals("Hello", iter.next().toString());
assertFalse (iter.hasNext());
}
/* Now let's try with another set of Objects
* Actual Generic Parameters in this case are Animal objects.
* Type erasure and Generically derived type is Animal here.
* */
public void testElements3() {
OopList OopLT = new OopList ();
assertTrue (OopLT.isEmpty());
OopListIterator iter1 = new OopListIterator (OopLT);
assertFalse (iter1.hasNext());
Animal me = new Animal("Tiger", 33, true);
Animal horse = new Animal("Horse", 10, true);
Animal Parrot1 = new Parrot ("P", 3, true);
OopLT.add(Parrot1);
OopLT.add(horse);
OopLT.add(me);
OopListIterator iter = new OopListIterator (OopLT);
assertFalse (OopLT.isEmpty());
assertTrue (iter.hasNext());
assertTrue (iter.hasNext());
assertEquals("Name: Tiger Age: 33 Pet: true", iter.next().toString());
assertEquals("Name: Horse Age: 10 Pet: true", iter.next().toString());
assertEquals("Name: Parrot Age: 3 Pet: true", iter.next().toString());
assertFalse (iter.hasNext());
OopListIterator iter2 = new OopListIterator (OopLT);
assertTrue (iter2.hasNext());
assertTrue (iter2.hasNext());
assertEquals("Name: Tiger Age: 33 Pet: true", iter2.next().toString());
assertEquals("Name: Horse Age: 10 Pet: true", iter2.next().toString());
assertEquals("Name: Parrot Age: 3 Pet: true", iter2.next().toString());
}
}
// Adopted from: http://www.cs.huji.ac.il/course/2005/oop/lecture-slides.html
//couldn't find a better way to do this...
public void double2 ( ) {
/* Invariant is L with 2 first ones and rest*/
ListNode q, w;
w = q = new ListNode (null);
for (ListNode p = myHead; p != null; p = p.myRest) {
q.myRest = new ListNode(p.myFirst, p);
q = q.myRest.myRest;
}
myHead = w.myRest;
/*ListNode p = myHead;
ListNode p1 = myHead.myRest;
ListNode p2 = myHead.myRest.myRest;
myHead = new ListNode (p.myFirst, p);
myHead.myRest.myRest = new ListNode (p1.myFirst, p1);
myHead.myRest.myRest.myRest.myRest = new ListNode (p2.myFirst, p2);
*/
}
public void double3 ( ) {
ListNode w;
w = new ListNode (myHead.myFirst);
for (ListNode p = myHead; p != null; p = p.myRest) {
w.myRest= new ListNode(p.myFirst, p);
w = w.myRest.myRest;
System.out.println(this.toString());
}
myHead = new ListNode (myHead.myFirst, myHead);
}
Well, wasted half a day yesterday by forgetting my Scheme. Finally,
A&S came to the rescue, somehow remembered after wasting a lot of time,
that 'append!' was one of the examples in that book and the same stuff
basically can be done in Java too..
Here is the Scheme version:
(define (append! x y)
(set-cdr! (last-pair x) y)
x)
Here last-pair is a procedure that returns the last pair in its argument:
(define (last-pair x)
(if (null? (cdr x))
x
(last-pair (cdr x))))
From there the Java version for append! or what we call, descructively
appending a list to another one while not instantiating another one is easy.
Though we have to instantiate a new ListNode...
ListNode LastP = lastPair(list1);
LastP.setNext(list2); //setNext is set-cdr!
return list1;
Here's the helper for Java...
public static LNode lastPair(ListNode y){
if (y.next().isEmpty()){
return y;
} else
return lastPair(y.next());
}
Another instersting one is the Reverse method:
Scheme Version:
(define (reverse L)
(reverse-helper L '( )) )
(define (reverse-helper L so-far)
(if (null? L) so-far
(reverse-helper (cdr L) (cons (car L) so-far)) ) )
Java version works the sameway if we are writing the recursive one:
return reverseHelper (list1.next() , new LNode (list1.data(), sofar) );
Deconstructing a Scheme recursive function and implementing it as a java method..
In scheme, to add an element to the end of the list we have the following procedure:
(define (add-to-end-of-list list a)
(if (null? list) '(a)
(cons (car list) (add-to-end-of-list (cdr list) a)) ) )
This is recursive. And answer returns after it hits base case and everybody is happy!
Ecept for the stack I guess.
Amazing thing is, we can pretty much do the same in Java!
public Lnodeadd (Object a) {
return LnodeAddHelper (this, a);
}
private static LnodeAddHelper (Lnode L, Object a) {
if (L.Empty()) {
return new Lnode (a);
} else {
return new Lnode(L.first(), LnodeAddHelper (L.rest(), a));
//the above line is mind blowing or what???
}
}
Here Lnode is the singly linked List. first() is car, rest() is cdr and the Lnode constructor is the cons.
Finished reading 'Anasi Boys' By Neil Gaiman. Good book, though I kinda felt
that towards the end it could've been made shorter, it just dragged on for a
bit towards the end...
A gripping book nonetheless. Had to read it through all night last night to finish
it, couldn't put it down! :(
Gives you some new ways at looking at things...it does, though!
Here's the Amazon link...
http://www.amazon.com/Anansi-Boys-Novel-Neil-Gaiman/dp/006051518X
When we are creating an Iterator for a class, we are actually calling
on the nested/inner class maybe. If the iterator is inside the main class,
it makes perfect sense to put the iterator there with its hasNext(), hasElement(),
initIterator(), and other methods...
So we create an iterator like this and looks like a method call but it's a call
on the nested class...
Iterator iter = mySomeKindOfList.myListIterator ( );
Finished reading 'The Univited'..also known as 'The Banquet Bug':
http://www.amazon.com/BANQUET-BUG-Geling-Yan/dp/1401366651
Good book. Read it in 2 days. A very fast read and very interesting idea.
You feel for the 'stupid' hero. It depicts the reality of China and not the
all embracing positive productive image that is projected by the powers that be!
Though I found the backcover story line to not follow the actual story. Don't know
if the book went through severe editorial stuff since it's first publication or
something or just that the back cover story line was written by some guy who only
heard about the book and actually didn't get to read it! That's a posibility too!
In any case, quite a book to enjoy. Geling Yan did a good job. Though in some
places there were heavy signs of editing that made for some impression of
disjointedness. Don't know if this was a literary mechanism or problem. Who can tell.
At least, I liked what I read. You get to really like the characters and the writer
makes you care for them. The books dishes the journalist for some good measure. But
given the state of the Media in the world, who can blame her? What her hero does,
is I guess is done by many a journalist where they have the trappings of Journalism
and in the mean time they just copy and paste somebody's propaganda....
Don't believe in any 'ISM' but making an exception here, perhaps the SUN guys will
change the word some time later as all 'ISM' brings bad news in the end. Maybe,
PolyMorphISM is no exception to this 'invariant'!
For the following discussion, we have to classes, Super and Sub which extends the
Super class, both class defines the same non-static method (same signature, return
type) within itself, we call this method methodx
Super A = new Sub ();
A.methodx();
Calls the methodx of the Sub class, _not_ the Super class.
This is dynamic binding at work. Most important thing to remember is that Dynamic
Type is the KING!
Doesn’t matter what the static Type is! The method to call at run time WILL BE
based on the dynamic type.
Thus in the above, when we do the method call, the ‘methodx’ of the Sub class will
be called even though static type is Super. But we don’t care about static type with
dynamic binding.
Sub B = new Super ();
This results in compile time error, since we can not go from low to high in terms of
assignment. The way I put it is that the servant can not wear the Master’s shoes!
(At least according to Java Compiler). If the Super class is the Master and the Sub
class is the slave, then Sub class can not own property titles of the Master. Here
we extend the analogy this way....the Super class is the Master and objects of that
class are the property of the Master. The static type of the Parent class is
actually the title deeds on the property. So, here we are thinking that, in terms of
references, or arrows, those are actually property titles and the actual property is
the actual instantiated objects, while the Master is actually the Class itself. Ok…
maybe convoluted. But stay with me, I’m making this up as we go along! :) In any
case, in terms of the analogy, Static type Sub is the slave and all variables of its
type (like B) can only be of deeds to its own property (meager though they maybe or
not…after all can slaves really own ANYTHING? They can not, only they seem to do so
some times, which is an illusion. This hypothesis will be verified and testified by
Java compiler in a little while as we will see!), i.e. instantiated objects of its
own type (Sub class type). If it tries otherwise, Java will stop it. Thus we will
get a compile error.
Super C = new Super ();
((Sub) C).methodx();
This results in a run time error. Here we have the Master and all, but we try to
cast the master as a slave. This passes through compiler, as they are all beings of
the same world. However, when running it will found that the dynamic type is also
Super so, the compiler doesn’t know what to do in such a situation. Going back to
the Master slave analogy, we have a proper Master here with both static and dynamic
type as Master, thus when we ask it to do slave work, it says, “I don’t do no slave
work!” (you can see how the Master picks up some slave idioms in the in the mean
time…)
However if the casting was like this…
Super D= new Sub ( );
((Sub) D).methodx ( );
The everything is OK, as then the Master is cast into slave and it was a slave all
along! The dynamic type was Sub! We don’t even have to cast…as D was a slave by it’s
dynamic type all along, and we know that dynamic type RULES!!!
Sub E = new Sub ();
((Super) E).methodx();
Here still, same stuff, just have to remember that dynamic type is what matters. We
can cast the slave E to be the of the Master race but when he goes to work, we see
that all he knows is slave work and none of the Master’s work. Thus, the methodx
from the Sub class gets called. Since even though we case E, we just change the
Static type by the cast, we can not change the Dynamic type and the dynamic type is
still pointing at a Sub object…
So the take away point is:
1. Dynamic type is all that matters on method call, I mean non-static methods.
2. Sub class static type var can NOT point to Super objects.
3. Super static type var CAN point to Sub objects.
In terms of Casting:
1. Casting Super var to Sub is NOT OK, where the dynamic type was Super
2. Casting to Super of Sub var is OK, but doesn’t gain us anything, while
the dynamic type was Sub object anyway.
Simple clarity, left side of assignment is static type, right side is dynamic type
(which contains the ‘new’ keyword).
import java.util.*;
public class HashSetIterator {
/**
* @A.J, CH 15
*/
public static void main(String[] args) {
HashSet s = new HashSet();
s.add("House");
s.add("of");
s.add("fun");
s.add("believe");
s.add("Shame");
s.add("woke");
System.out.println("The Set Contains: ");
Iterator i = s.iterator();
while (i.hasNext())
System.out.println (i.next());
System.out.println("****End of Contents***");
i.remove();
System.out.println();
System.out.println("The Set _now_ Contains: ");
Iterator z = s.iterator();
while (z.hasNext())
System.out.println (z.next());
System.out.println("****End of Contents***");
System.out.println();
System.out.println();
System.out.println("The Java Instructions have come to an END.");
}
}
/*
The Set Contains:
of
woke
House
fun
believe
Shame
****End of Contents***
The Set _now_ Contains:
of
woke
House
fun
believe
****End of Contents***
The Java Instructions have come to an END.
*/
import java.io.PrintStream;
import java.util.*;
public class ReadAndReverse {
static void readAndReverse (Scanner input, PrintStream output) {
ArrayList L = new ArrayList ();
while (input.hasNext())
L.add(input.next());
for (int k = L.size() - 1; k >= 0; k -=1)
output.printf("%s ", L.get(k));
}
public static void main (String [] args) {
Scanner inp = new Scanner (System.in);
readAndReverse (inp, System.out);
}
}
//insert into an array
public void insert (int nInt, int pos) {
myV[myCt] = myV [myC-1]; //increase the interesting sub-array size
int k = myV.length ;
for (int i = k-1; i >= 0; i--) {
if (i == pos) {
myV[i] = nInt;
break; // done, get out!
}
myV[i] = myV[i-1]; //shift the values down
}
myCt++; //increase the instance var...
}
public class IntList {
// Names of simple Containers
public int head;
public IntList tail;
// Constructor function
/** List Cell containing (HEAD, TAIL). */
public IntList (int head, IntList tail) {
this.head = head; //Scheme car
this.tail = tail; //Scheme cdr
}
/* Converts an Array of Integers into a Linked List with
* the same elements.
* @param: an Array of integers with > 1 elements
*/
static IntList makeList (int a []) {
IntList X, Z;
X = new IntList (a[0], null);
int i;
for (i = 1, Z = X; i < a.length ; i++, Z = Z.tail){
Z.tail = new IntList (a[i], null);
}
return X;
}
/* Recursive Version */
static IntList makeListr (int a []) {
int i = 0;
IntList X, Z;
X = new IntList (a[0], null);
Z = X;
Z = makelistrhelper (X, a, ++i);
return X;
}
static IntList makelistrhelper (IntList Z, int a [], int i) {
if (i > a.length -1 ){
return Z;
} else {
Z.tail = new IntList (a[i], null);
return makelistrhelper (Z.tail, a, ++i);
}
}
static int countList (IntList Z) {
int countL = 0;
countL = countListH (Z, countL);
return countL;
}
static int countListH (IntList Z, int countL){
if (Z == null)
return countL;
else {
return countListH (Z.tail, ++countL);
}
}
static void printList (IntList Z) {
int i = 0;
IntList M;
for (M = Z; M != null; M = M.tail ) {
System.out.println("Head" + "-" + i +" ---- " + M.head);
i++;
}
}
/** List of all items in P incremented by n. */
static IntList incrList (IntList P, int n) {
if (P == null)
return null;
else return new IntList (P.head+n, incrList (P.tail, n));
}
/** Iterative version */
static IntList incrListIterative (IntList P, int n) {
if (P == null)
return null;
IntList result, last;
result = last
= new IntList (P.head+n, null);
while (P.tail != null) {
P = P.tail;
last.tail = new IntList (P.head+n, null);
last = last.tail;
}
return result;
}
/** List of all items in P incremented by n. May destroy original. */
static IntList dincrList (IntList P, int n) {
if (P == null)
return null;
else {
P.head += n;
P.tail = dincrList (P.tail, n);
return P;
}
}
/** For version */
static IntList forDincrList (IntList L, int n) {
// for is more than a loooooooooper.
for (IntList p = L; p != null; p = p.tail )
p.head += n;
return L;
}
/** The List resulting from removing all instances of X
* from L non-destructively
*/
static IntList removeAll (IntList L, int x){
if (L == null)
return null;
else if (L.head == x)
return removeAll (L.tail, x);
else
return new IntList (L.head, removeAll (L.tail, x));
}
static IntList removeAllIterative (IntList L, int x) {
IntList result, last;
result = last = null;
for ( ; L != null; L = L.tail){
/* L != null and I is true. */
if (x == L.head)
continue;
else if (last == null)
result = last = new IntList (L.head, null);
else
last = last.tail = new IntList (L.head, null);
}
return result;
/** Here, I is the Loop Invariant:
* Result of all elements of L0 not equal to X up to
* and not including L, and last points to the last
* elements of result, if any. We use L0 here to mean
* "the original value of L." *
*/
}
}
Here we go again...Pascal Triangles once more...by popular demand only....
public class PascalTriangle {
public static int [] [] pascalTriangle (int n) {
int [][] pt = new int [n][];
for (int i = 0; i < n; i++){
pt[i] = new int [i + 1];
pt[i][0] = 1;
for (int j = 1; j < i; j++) {
pt[i][j] = pt[i - 1][j - 1] + pt [i -1][j];
}
pt[i][i] = 1;
}
return pt;
}
public static void printTriangle (int x [][], int n) {
for (int i = 0; i < n; i++){
System.out.println();
for (int k = 0; k <= i; k++ ) {
System.out.print (" " + x[i][k]);
}
}
}
public static void getPascalTriangle (int n) {
printTriangle (pascalTriangle (n), n);
}
public static void main(String[] args) {
int G = 30;
getPascalTriangle(G);
}
}
The fabulous Sieve of EROTOSTHENES once more, if you are already not too sick of it by now!
public class PrintPrimes {
public static void printPrimes (int n) {
boolean [] prime = new boolean [n + 1];
int i;
for (i=2; i <= n; i++ ) {
prime[i] = true; }
for (int divisor = 2; divisor * divisor <= n; divisor ++) {
if (prime[divisor]) {
for (i = 2* divisor; i <= n; i = i + divisor) {
prime [i] = false; }
}
}
for (i = 2; i <= n; i++ ) {
if (prime[i]) {
System.out.print (" " + i);
}
}
}
public static void main(String[] args) {
int G = 10; PrintPrimes.printPrimes(G);
}
}
public class IntListTest {
public static void main (String [] args) {
int [] a = new int [] { 3, 6, 19, 71 };
IntList X = new IntList (0, null);
X = X.makeList (a);
System.out.println ("List created! ");
X.printList(X);
IntList Y = new IntList (0, null);
int [] x = new int [] { 3, 2, 32, 57, 72, 98, 32, 323 , 232};
Y = Y.makeListr(x);
System.out.println ("List created! ");
Y.printList(Y);
System.out.println ("List Count: " + Y.countList(Y));
}
}
%java IntListTest
List created!
Head-0 ---- 3
Head-1 ---- 6
Head-2 ---- 19
Head-3 ---- 71
List created!
Head-0 ---- 3
Head-1 ---- 2
Head-2 ---- 32
Head-3 ---- 57
Head-4 ---- 72
Head-5 ---- 98
Head-6 ---- 32
Head-7 ---- 323
Head-8 ---- 232
List Count: 9
The methods missing from yesterday's post...
public class IntList {
// Names of simple Containers
public int head;
public IntList tail;
// Constructor function
/** List Cell containing (HEAD, TAIL). */
public IntList (int head, IntList tail) {
this.head = head; //Scheme car
this.tail = tail; //Scheme cdr
}
/* Converts an Array of Integers into a Linked List with
* the same elements.
* @param: an Array of integers with > 1 elements
*/
static IntList makeList (int a []) {
IntList X, Z;
X = new IntList (a[0], null);
int i;
for (i = 1, Z = X; i < z =" Z.tail){" tail =" new" i =" 0;" x =" new" z =" X;" z =" makelistrhelper"> a.length -1 ){
return Z;
} else {
Z.tail = new IntList (a[i], null);
return makelistrhelper (Z.tail, a, ++i);
}
}
static int countList (IntList Z) {
int countL = 0;
countL = countListH (Z, countL);
return countL;
}
static int countListH (IntList Z, int countL){
if (Z == null)
return countL;
else {
return countListH (Z.tail, ++countL);
}
}
static void printList (IntList Z) {
int i = 0;
IntList M;
for (M = Z; M != null; M = M.tail ) {
System.out.println("Head" + "-" + i +" ---- " + M.head);
i++;
}
}
}
Some Simple Linked List operations:
public class IntList {
// Names of simple Containers
public int head;
public IntList tail;
// Constructor function
/** List Cell containing (HEAD, TAIL). */
public IntList (int head, IntList tail) {
this.head = head;
this.tail = tail;
}
/** List of all items in P incremented by n. */
static IntList incrList (IntList P, int n) {
if (P == null)
return null;
else return new IntList (P.head+n, incrList (P.tail, n));
}
/** Iterative version */
static IntList incrListIterative (IntList P, int n) {
if (P == null)
return null;
IntList result, last;
result = last
= new IntList (P.head+n, null);
while (P.tail != null) {
P = P.tail;
last.tail = new IntList (P.head+n, null);
last = last.tail;
}
return result;
}
/** List of all items in P incremented by n. May destroy original. */
static IntList dincrList (IntList P, int n) {
if (P == null)
return null;
else {
P.head += n;
P.tail = dincrList (P.tail, n);
return P;
}
}
/** For version */
static IntList forDincrList (IntList L, int n) {
// for is more than a loooooooooper.
for (IntList p = L; p != null; p = p.tail )
p.head += n;
return L;
}
/** The List resulting from removing all instances of X
* from L non-destructively
*/
static IntList removeAll (IntList L, int x){
if (L == null)
return null;
else if (L.head == x)
return removeAll (L.tail, x);
else
return new IntList (L.head, removeAll (L.tail, x));
}
static IntList removeAllIterative (IntList L, int x) {
IntList result, last;
result = last = null;
for ( ; L != null; L = L.tail){
/* L != null and I is true. */
if (x == L.head)
continue;
else if (last == null)
result = last = new IntList (L.head, null);
else
last = last.tail = new IntList (L.head, null);
}
return result;
/** Here, I is the Loop Invariant:
* Result of all elements of L0 not equal to X up to
* and not including L, and last points to the last
* elements of result, if any. We use L0 here to mean
* "the original value of L." *
*/
}
}
// Copy of blogs from some other place. That service is really frustrating. Relocating here....
October 7, 2007 - Sunday
Constructor variables!
Instance variables should not be re-declared in the constructor.
This is easy to do mistakenly...For example:
public class Mt{
int height;
int length;
int iRep;
// the following is the wrong way to do it. We are basically redeclaring the instance
// vars and height, length, iRep all will be set to zero!!!!!!!!!!
// Because height, length and iRep will be set to local variables, the constructor is
// nothing more than a method and as such, these variables' set values will die after the
// constructor is finished and we will revert back to the default values for these variables
// which is zero as the class did not initialize them to anything!
// height = length = iRep = 0 is the result of the following!
public Mt (int ht, int ln) {
int height = ht;
int length= ln;
int iRep = iRepC (ht, ln);
}
// Correct way:
// get rid of the type declarations..
// The type is already declared in the class.
// No need to redeclare...
public Mt (int ht, int ln) {
height = ht;
length= ln;
iRep = iRepC (ht, ln);
}
4:43 AM -
Junit Test Case Framework Current mood: calm
Bare Skeleton junit TestCase frame work. We absolutely need the following.
First we need to import the junit.framework.TestCase:
import junit.framework.TestCase;
Then this is the TestClass that is created by Eclipse®. The Class that we are working with here is called 'Whatever'. So, this 'Whatever' Class will extend the TestCase class...
public class WhateverTest extends TestCase {
The first test is for the Constructor of the class. Imagine there is some static int in the Whatever class that is a class variable, and instantiating any object of whatever class would set this to 1000. And the what() method of Whatever Class would return this value. So, we create a testConstructor method which would create the object 'w' and then assertTrue on checking to see if Whatever.what() returns the expected value of 1000.
public void testConstructor ( ) { Whatever w = new Whatever ( ); assertTrue (Whatever.what () == 1000); }
Then we have other method tests. Let's have a test on some method of the 'Whatever' class called whyWhatever(). Why whyWhatever does something to that same class var and should return 2000.
public void testIncrement ( ) { Whatever w = new Whatever ( ); w.whyWhatever( ) ; assertTrue (w.what() == 2000); } If everything's going Ok, then the test cases will succeed. And we will have the green bars in Eclipse after running the Junit Test cases.
2:12 AM
October 6, 2007 - Saturday
Arguments are passed by Value in Java!!!!!!! Current mood: curious
Arguments in Java are all passed by value. This implies that each argument is copied into the corresponding method parameter in the method being called. If the parameter is a reference, the mechanics of method operation on that parameter is the same when an assignment statement involves two references. In box-and-pointer terms, the copy results in two arrows pointing to the same box. The method call may work with the object reference and do all sorts of things to the reference(s). But at the end of the day, the method parameters live on the frame stack on the heap and they all die when the method is finished. Nothing persists!!!
What this means in reality is that an argument of a primitive type can't be changed in a method to which it is passed, since the method is working with not with the actual primitive but rather a copy of that primitive. A reference argument likewise can not be changed either, by the same token. However, variables in the referenced object can be changed.
In short for variables within an object to change, some kind of dot operator (.), will be there within the method body. It might not change stuff, but if you don't see the dot operator, then you know that nothing in the object will be changed in this method!
4:05 PM
Ok....set the spam meter high... Current mood: aggravated
http://profileedit.myspace.com/index.cfm?fuseaction=accountSettings.spam
but this is kind of bad as nobody else can send me invites now, the admin
should just kick out sex peddlers out of this space or open up a mySEXspace.com or something for people inclined towards that kind of thing!
12:37 AM -
0 Comments -
0 Kudos -
Add Comment -
Edit -
Remove
What are all these stupid invites??? Current mood: angry
Getting a whole bunch of spam! Just checked my email and there were like 50 emails talking about wanting to be my 'friend'! All of those some scam, it's funny that there is a option to select all and deny but not the option to report the whole bunch as scam/spam! Myspace should have it, otherwise, this website will become unusable. The admin should do something about these spammers. Why send these objectionable peoples' pics and stuff to my control panel or send me email!?!?!
12:31 AM
Object Refernces..... Current mood: amused
Just to reiterate something that is pretty obvious but seems to trip you off
all the time, is this issue with object references. Say we have two objects
xA and xB. And each has a two element array. Lets call them xA1, xA2 and
xB1 , xB2.
Then if we make the following assignments...
xB1 = xA1;
xB2 = xA2;
And then further do the following:
xA2 = xA1;
Then if we follow the object reference logic, xA1, xA2 and xB2 all would
have the same values but xB1 would continue to have the old value of xA2!
If we draw the diagram out, it all makes sense!
xA -------> xA1 <----------xB2 <--------------xB ---------->xA2 <----------xB1 <-------------- After the last set of assignments: xA---------->xA1 <--------- xA2 ^ xB2 ---------------- xB---------->xB1------------>(old) xA2
This is because after the first set of assignemnts, the object pointed to by
xA2 and xB1 are the same, however, when we assign the reference given
by xA2 to some other object, this does not automatically reassign the reference
given by xB1. They were pointing to the same thing, however, after
re-assignment of xA2, xB1 is still pointing to it's old thing and xA2 has moved
on. The crutial thing to understand is that xA2 and xB1, i.e. objects or arrays
are not actually values but rather references and thus the '=' sign is not
mathematically equal sign, it is ASSIGNMENT! And since these are object
reference assignments, when one changes to refer to another object, the other
does NOT change!
p.s. the diagrams are simplifications, xA1 or xB1 does not point to each other
or something like that, what is simplified is that, xA1 points to something
and xB1 points to that same thing or some other thing. They can't point to each
other they can only point to some same object on the garbase collectible heap!
..........and that's the whole point!
11:56 AM
October 5, 2007 - Friday
String Compare Blues... Current mood: bouncy
Finally got the string compare joy thing figured out...
The following would return true for mString == FUSD and s == USA.
***********
return (mString.substring(1).compareTo (s) == 0) ? true : false ;
***********
This is the zems of pearl from javadocs (javadocs is ®of your buddy Sun and I guess opensource and all that, so, quoting should be kosher)
If the (javadocs - following) makes 100% sense to you then you must be
compareTopublic int compareTo(
String anotherString)
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the
equals(Object) method would return true.
substringpublic
String substring(int beginIndex)
Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
substringpublic
String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
charAtpublic char charAt(int index)
Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
3:03 PM
Object recursion
Phew!!!!!!!! This code finally worked...my first recursive objects.........took me
a while to figure this out. Especially confusing was to get the right object
to call the recursive call on!
.r{}*
There's some junk in this code and needs to get polished up, but it's working
and that's good enough for now...As we all know, we can chase down the
perfect code all day long and possibly spend a week on a ten liner but
have to move on...In my thinking, it's also very important to stop at some point
from the dangerous recursive call to
beatify(timeAndResourse);
:)
*/
.r{}* @param Call with this and this.mBalance
* this is tail recusive, in that f() returns
* itself with a smaller problem.
*/
public int recursiveBalance (Account someAccount , int lance) {
if (someAccount.parentAcc != null) {
Account tmpy = new Account(0);
tmpy = someAccount;
return recursiveBalance (tmpy.parentAcc, lance +
tmpy.parentAcc.mBalance) ;
} else {
return lance + mBalance;
}
}
.r{}* Putting the code here so that I can come back later
* and appreciate how stupidly I coded, way back when!
* err....hopefully...of course!
*/
10:40 AM
October 4, 2007 - Thursday
The Indredible Lightness of Being Current mood: depressed
Want to recommend a great book that I finished up...
Incredible lightness of being by
Milan Kundera
A great book to ponder on. There are some really thought provoking motifs
explored in the book.
After reading this book you keep on thinking, "must it be so?".
And that's a very pertinent question in anybody's life.
Also another theme about the fact that we get to live only once and whatever
we do is like an actor temporizing without rehearsing is very interesting.
Reminds you of the
Doors line:
Into this house we're bornInto this world we're thrownLike a dog without a boneAn actor on a loan
It seems emimently possible that there are no second chances and the
trajectories that our lives take has no back tracing. We get one chance
every moment and at the end of the end, what can we do but do what
we do???
2:00 AM -
I/O example
.r{}* input and output examples
* first is just reading a line from keyboard and spewing it back.
* ISR takes System.in and BR takes this and we assign this to the BR object
* keybd
*/
import java.io.*;
public class SS01 {
.r{}*
* @param keybd and call readLine() on it and print it
*/
public static void main(String[] args) throws Exception {
BufferedReader keybd = new BufferedReader (new InputStreamReader (System.in));
System.out.println(keybd.readLine());
}
}
.r{}* Reading from a webpage.
*/
import java.io.*;
import java.net.*;
public class SSWebLine {
.r{}*
* @param takes an URL as arg and prints out on the console
*/
public static void main(String[] args) throws Exception {
URL u = new URL ("http://www.yahoo.com");
InputStream Ins = u.openStream();
InputStreamReader Isr = new InputStreamReader(Ins);
BufferedReader yahooCom = new BufferedReader (Isr);
System.out.println(yahooCom.readLine());
}
}