Java数组参数链表构造器写法是否正确?求代码校验和修改建议
现有代码问题梳理
- 冗余成员变量:
int[] array、Node other两个成员变量没有存在必要,链表仅靠head头结点即可完成所有操作,保留只会增加不必要的内存开销和逻辑出错概率。 - 数组参数构造器未实现核心逻辑:当前代码仅创建了一个和入参数组等长的空数组赋值给成员变量,完全没有将数组元素转为Node节点、串成链表的逻辑,不符合需求。
- 构造器数量不足:要求实现3个不同构造器,当前仅完成无参、数组参数2个,缺1个。
修正后代码示例
import java.util.Random; // 建议链表实现类单独命名,测试类拆分出去,这里先保留你原来的类名 public class LinkedListOfIntsTest { Node head; // 删掉无用的array、other成员变量 private class Node { int value; Node nextNode; public Node(int value, Node nextNode) { this.value = value; this.nextNode = nextNode; } } // 构造器1:无参构造,初始化空链表 public LinkedListOfIntsTest() { head = null; } // 构造器2:单初始值构造,初始化只有一个元素的链表 public LinkedListOfIntsTest(int initValue) { head = new Node(initValue, null); } // 构造器3:int数组参数构造,把数组所有元素存入链表 public LinkedListOfIntsTest(int[] other) { // 入参非空校验 if (other == null || other.length == 0) { head = null; return; } // 头结点初始化 head = new Node(other[0], null); Node current = head; // 遍历剩余元素尾插成链 for (int i = 1; i < other.length; i++) { current.nextNode = new Node(other[i], null); current = current.nextNode; } } // 后续可以在这里补充要求的指定方法,比如add、remove、get、size等 }
后续调整建议
- 建议拆分职责:把链表实现类重命名为
LinkedListOfInts,单独新建LinkedListOfIntsTest类写测试逻辑,结构更清晰。 - 测试逻辑可以覆盖这些场景:空数组入参、单元素数组入参、多元素乱序数组入参、空链表调用方法、随机增删改查后校验链表元素和预期是否一致。
内容的提问来源于stack exchange,提问作者user16854661
相关产品推荐
相关产品推荐

