From my comment:
If you want to use an enhanced for loop i.e. a foreach then you should do the null check inside it.
nameList = null;
listNode current = null;
for (String person : names) {
if (nameList= null) {
nameList = new listNode(names.get(0));
current = nameList;
} else {
current.next = new listNode(person);
current = current.next;
}
}
Another recommendation: use CamelCase for your class names for better code readability, listNode
class should be ListNode
and listManager
class should be ListManager
.
By @corsiKa's comment, this won't be a best suited case to use an enhanced for
loop (in fact, this really depends on how many items we're talking about to measure the performance impact, but that's outside of this question). To make it a more generic algorithm that can even supports List
(the generic interface implemented by ArrayList
), you can use an Iterator
instead:
Iterator<String> iterNames = names.iterator();
if (iterNames.hasNext()) {
nameList = new listNode(iterNames.next());
listNode current = nameList;
while (iter.hasNext()) {
current.next = new listNode(iterNames.next());
current = current.next;
}
}
Note that if you still want to stick with the enhanced for
loop approach, there's no way to remove the null
check from it.