July 28, 2008

Chapter: Holding Your Objects

Create a new class called Gerbil with an int gerbilNumber that's initialized in the constructor. Give it a method called hop() that displays which gerbil number this is, and that it's hopping. Create an ArrayList and add Gerbil objects to the List. Now use the get() method to move through the List and call hop() for each Gerbil.

As we proceed deeper into the book, completing the exercises using multiple languages exposes the differences more clearly. In my opinion Lisp and Java are completely different beasts, with Python combining Lisp's ease of programming with Java-like syntax.

In Java:
package chapter.holdingYourObjects;

import java.util.*;

class Gerbil {
private int gerbilNumber;

Gerbil(int gerbilNumber) {
this.gerbilNumber = gerbilNumber;

public void hop() {
System.out.println("Gerbil " + gerbilNumber + " is hopping");

public class Exercise1 {
public static void main(String[] args) {
ArrayList<Gerbil> gerbils = new ArrayList<Gerbil>();
for(int i = 0; i < 10; i++)
gerbils.add(new Gerbil(i));

for(int i = 0; i < gerbils.size(); i++)

In Python:
class Gerbil:
def __init__(self, gerbilNumber):
self.gerbilNumber = gerbilNumber
def hop(self):
print "Gerbil " + str(self.gerbilNumber) + " is hopping"

gerbils = []
for i in range(10):

for i in range(len(gerbils)):

In Lisp:
(defclass Gerbil ()
((gerbil-number :accessor gerbil-number
:initarg :num)))

(defmethod hop ((g Gerbil))
(format t "Gerbil ~d is hopping~%" (gerbil-number g)))

(defparameter *gerbil-list*
(loop for i from 0 to 9 append
(list (make-instance 'Gerbil :num i))))

(loop for a-gerbil in *gerbil-list* do (hop a-gerbil))