Okay so I have some questions about LinkedList. I'm doing an assignment on LinkedList and I noticed in the java API that there is a get(int index) method built in for LinkedList. From what I was reading LinkedList is set up like this node1->node2->node3-> where each node has reference to another node. I haven't read anywhere that linkedList keeps track of each element(like lets say Array where you can call array[1].toString() and it will return the contents at that position). From what I've been reading it has references to front and back and each of these nodes has references to each other. So if I call LinkedList.get(1)...what would it return? Node1? Or is it like Array starting at position 0. If anybody could clear this up that would be great.

Thanks :)

The API reference says

public E get(int index)
Returns the element at the specified position in this list.

so it would return just element/node number 1 (which is the second node in the list - indexes start at 0)

A quick look at the source code shows how it's done - the essential part goes like this

Entry<E> e = header;
        ...
        for (int i = 0; i <= index; i++)
        e = e.next;
        ...
        return e;

So, no, it doesn't keep track of the elements in an array or anything like that. It just starts from the first node and counts its way along the links to reach the desired element.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.