How can I convert an array to a list without using Arrays.asList() method or Java List Interface

Crespo :

I got my Node class:

public class Node <T> {

    private Node<T> next;
    private T element;

    public void setElement(T element) {
        this.element = element; 
    }

    public T getElement() {
        return element;
    }

    public Node<T> getNext() {
        return next;
    }

    public void setNext(Node <T> next) {
        this.next= next;
    }
}

And also I have my List class:

public class List <T> {

Node<T> first;
Node<T> last;

...on which I can do various things like adding elements to my list or replacing them, erase some elements, see the size of my list etc. One example of these methods would be addFirst().

public T addFirst(T element) {

    Node<T> aux;

    if (isEmpty()) {
        aux = new Node<>();
        first= aux;
        lsat= aux;
        aux.setElement(element);
    } else {
        aux = new Node<>();
        aux.setElement(element);
        aux.setNext(first);
        first= aux;
    }

    return first.getElement();
}

I am only missing one method convert an array to a list obviously with the previous mentioned restrictions.

adxl :

One solution is to loop through the array and simply fill you List:

// your array of Nodes
Node<?>[] nodeArray = new Node[]{node1,node2,node3,node4,node5};

// your List
List<?> myList = new List<>();

for(Node<?> node : nodeArray)
{
    myList.addLast(node); // use addLast() to keep the same order as the array
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=341963&siteId=1