Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Stuck with Java method

Name: Anonymous 2007-02-12 5:54

Hello, I am currently working on a Java program and I have come across a bit of a problem. I am using an interface and two classes to make a list of objects. The program currently includes an interface List, a class ConsList which implements List and contains an object "first" and a ConsList "rest", as well as a class EndList implementing List which contains an object "last" and is used to terminate the list. An example of use would be:
List l = new ConsList(foo,new ConsList(foo2, new EndList(end)));

All classes implementing List need to have a shiftRight(object o) method, which puts "o" at the beginning of the list, and removes the last object from the list. I have been trying to write this for a while now, but as I am not exceptional at Java the proper method definition continues to elude me. I would greatly appreciate any help. Thank you in advance.

Name: Anonymous 2007-02-13 10:45

Dear OP, I was feeling generous and I wanted to piss off the 'DO YOUR OWN HOMEWORK' faggots, so I installed jdk and did your homework for you. Note that I've used null to mark the end of the list instead of inventing a magic singleton class. The main method acts as a test case/usage example.

public class ConsList //implements List
{
    private Object car;
    private ConsList cdr;

    public ConsList(Object car, ConsList cdr) {
        this.car = car;
        this.cdr = cdr;
    }

    public ConsList(Object car) {
        this.car = car;
        this.cdr = null;
    }

    public Object head() {
        return car;
    }

    public ConsList tail() {
        return cdr;
    }

    public boolean isLast() {
        return cdr == null;
    }

    public ConsList init() {
        if(isLast()) {
            return null;
        } else {
            return new ConsList(car, cdr.init());
        }
    }

    public Object last() {
        if(isLast()) {
            return car;
        } else {
            return cdr.last();
        }
    }

    public ConsList shiftRight(Object o) {
        return new ConsList(o, init());
    }

    public static void main(String[] args) {
        ConsList foo = new ConsList("hello", new ConsList("world",
                    new ConsList("java", new ConsList("sucks"))));

        for(ConsList bar = foo.shiftRight("omg"); bar != null; bar = bar.tail()) {
            System.out.println((String)bar.head());
        }
    }
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List