チェーンテーブルのJava実装(ポインタの参照として内部クラスを使用)


class Element {
	private String name;
	private Element next;

	public Element(String name) {
		this.name = name;
	}

	public String getName() {
		return this.name;
	}

	public void setNextElement(Element next) {
		this.next = next;

	}

	public Element getNextElement() {
		return this.next;
	}

}

public class LinkDemo {
	public static void main(String args[]) {
		Element root = new Element("   ");
		Element elem1 = new Element("  1");
		Element elem2 = new Element("  2");
		Element elem3 = new Element("  3");
		Element elem4 = new Element("  4");

		root.setNextElement(elem1);
		elem1.setNextElement(elem2);
		elem2.setNextElement(elem3);
		elem3.setNextElement(elem4);

		print(root);

	}

	public static void print(Element elem) {
		if (elem != null) {
			System.out.print(elem.getName() + " --> ");
		}
		if (elem.getNextElement() != null) {
			print(elem.getNextElement());
		}
	}

}