Reputation: 69
A linked list has four nodes like below, i am trying iterate or traverse so i can return each node out like below... but my code just gives me the first node and doesn't get to the rest of them to return...
Cary, USA , Population: 40000
Raleigh, USA , Population: 34300
Apex, USA , Population: 60000
Durham, USA , Population: 34000
public T retrieveAll(TableInterface<City, String> inChart) {
Node tmp = head;
while(tmp != null) {
tmp = tmp.getNext();
return (T) head.getItem();
}
return null;
}
Upvotes: 2
Views: 123
Reputation: 641
Instead of returning in while
loop. Use some thing like add, to add in the ArrayList
.
Then at the end return that ArrayList
.
Upvotes: 2
Reputation: 1315
You are returning from your method in first iteration that is why you are getting only first Node.
To resolve this you should remove return from while loop and add your node in a collection while iterating and return that collection at the end.
Upvotes: 0
Reputation: 7109
A method can only return one thing at a time. Your method stops and returns when it hits your return
statement. To return more than one thing, you have to return it as an ArrayList
or an array.
Upvotes: 6