Question

I'm currently stuck with my implementation of a doubly linked list in Java. I implemented a few Methods (addLast/addFirst/size/Remove/removeLast/removeFirst/output). When I'm trying to add an element in my List the output will always be null. The code is just a raw version, pretty sure it has some mistakes in it. This is the Element class of the list:

public class Element<E> {
private Element<E> next;
private Element<E> prev;
//private String value;
private Object elem;
private E value;

public Element() {
    next = null;
    prev = null;
    value = null;
}

/**
 * @param value the value to set
 */
public void setValue(E value) {
    this.value = value;
}

/**
 * @return the value
 */
public E getValue() {
    return value;
}

public Object getElem() {
    return elem;
}

public void setElem(Object elem) {
    this.elem = elem;
}



/**
 * @return the next
 */
public Element<E> getNext() {
    return next;
}
/**
 * @param next the next to set
 */
public void setNext(Element<E> next) {
    this.next = next;
}
/**
 * @return the prev
 */
public Element<E> getPrev() {
    return prev;
}
/**
 * @param prev the prev to set
 */
public void setPrev(Element<E> prev) {
    this.prev = prev;
}

And here the class of the actual List with the addFirst and output method.

    public class List<E> {
private Element<E> first;
private Element<E> last;
private int size;
private Element<E> element = this.first;


/**
 * @param value uebergebener Wert fuer Listenelement
 * Fuege ein Listenelement an erster Stelle in die Liste ein
 */
public void addFirst(E value) {
    Element<E> newElement = new Element<E>();
    newElement.setValue(value);

    if (size == 0) {
        first = newElement;
        last = newElement;
    }
    else {
        newElement.setNext(first);
        first.setPrev(newElement);
        first = newElement;
    }
    size++;
}
public void output() {
    Element<E> temp = first;
    while (temp != null) {
        System.out.println(temp.getElem());
        temp = temp.getNext();
    }

And here the test class

    public static void main(String[] args) {
    List<String> newList = new List<String>();
    newList.addFirst("bla");


    newList.output();

I'm really stuck here. Is the constructor in the Element class wrong? thanks in advance!

Was it helpful?

Solution

First, it is confusing why you have both

private Object elem;
private E value;

What is the difference between those ? I would get rid of elem field and all related getters/setters.

Your real issue, however, is that you never set elem in your code, so simply change your output method to have

System.out.println(temp.getValue()); // instead of temp.getElem()

and it will work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top