Tim*_*ayB 2 java constructor readability linked-list
我正在尝试找出一种使用 for-each 循环构造 LinkedList 的方法。
我已经按照我目前的方式设置了并且它有效。我只是发现它非常难看,因为我必须在循环外部声明一个 listNode ,而其余部分则在 for 循环内声明。我无法摆脱这种感觉,这是一个笨拙的解决方案。
怎么写的——
private listNode nameList;
public listManager(ArrayList<String> names) {
nameList = new listNode(names.get(0));
listNode current = nameList;
for (int i = 1; i < names.size(); i++) {
current.next = new listNode(names.get(i));
current = current.next;
}
}
Run Code Online (Sandbox Code Playgroud)
我想使用 for-each 循环并使所有内容更具可读性,但我遇到了当 current 为空时尝试获取 current.next 的问题,因此我得到了 nullpointerException。有任何想法吗?
我多么希望它理想地喜欢它写的但不起作用-
listNode current = nameList;
for (String person : names) {
current.next = new listNode(person);
current = current.next;
}
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激!:)
从我的评论来看:
如果您想使用增强的 for 循环,即 foreach,那么您应该在其中进行 null 检查。
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;
}
}
Run Code Online (Sandbox Code Playgroud)
另一个建议:使用驼峰命名法作为类名,以获得更好的代码可读性,listNodeclass 应该是ListNode,listManagerclass 应该是ListManager。
根据@corsiKa的评论,这不是使用增强for循环的最适合的情况(事实上,这实际上取决于我们正在谈论的用于衡量性能影响的项目数量,但这不属于这个问题)。为了使其成为一个更通用的算法,甚至可以支持List(由 实现的通用接口ArrayList),您可以使用Iterator:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果您仍然想坚持使用增强for循环方法,则无法null从中删除检查。