如何让自定义LinkedList高效存储不同数据类型?
泛型实现通用LinkedList,支持多数据类型
你的问题核心是要让LinkedList适配多种数据类型,无需重复编写多个类,Java的泛型就是最优解——它能让你编写一次通用代码,适配任意引用类型,同时保证编译时的类型安全。
修改后的泛型Node类
public class Node<T> { private T data; private Node<T> link; public Node<T> getLink() { return link; } public void setLink(Node<T> link) { this.link = link; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
修改后的泛型LinkedList类
public class LinkedList<T> { private Node<T> root; public Node<T> getRoot() { return root; } public void add(T data) { if (root == null) { root = new Node<>(); root.setData(data); } else { Node<T> tmp = root; while (tmp.getLink() != null) { tmp = tmp.getLink(); } Node<T> n = new Node<>(); n.setData(data); tmp.setLink(n); } } public int size() { if (root == null) { return 0; } int count = 0; Node<T> tmp = root; while (tmp != null) { count++; tmp = tmp.getLink(); } return count; } public T get(int pos) { if (pos < 0 || pos >= size()) { throw new IndexOutOfBoundsException("The index " + pos + " is out of bounds."); } Node<T> tmp = root; for (int i = 0; i < pos; i++) { tmp = tmp.getLink(); } return tmp.getData(); } public void set(int pos, T data) { if (pos < 0 || pos >= size()) { throw new IndexOutOfBoundsException("The index " + pos + " is out of bounds."); } Node<T> tmp = root; for (int i = 0; i < pos; i++) { tmp = tmp.getLink(); } tmp.setData(data); } // 删除最后一个元素 public void delete() { if (root == null) { return; } // 处理链表只有一个元素的情况 if (root.getLink() == null) { root = null; return; } Node<T> tmp = root; while (tmp.getLink().getLink() != null) { tmp = tmp.getLink(); } tmp.setLink(null); } }
关键改动说明
- 在类名后添加
<T>声明泛型参数,T作为任意引用类型的占位符(也可替换为E这类语义化标识符) - 将所有硬编码的
BufferedImage替换为T,Node的link类型改为Node<T>,保证链表节点的类型一致性 - 修复了原
delete方法的潜在问题:原代码在链表仅含1个元素时无法正确清空root,现在新增了单独处理逻辑
使用示例
import java.awt.image.BufferedImage; // 创建存储BufferedImage的链表 LinkedList<BufferedImage> imageList = new LinkedList<>(); imageList.add(new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB)); // 创建存储Integer的链表(int是基本类型,需用包装类Integer,Java会自动完成装箱拆箱) LinkedList<Integer> intList = new LinkedList<>(); intList.add(10); intList.add(20); int value = intList.get(0); // 自动拆箱为int类型
泛型的核心优势:
- 无需重复编写多套类型专属的Node/LinkedList代码,复用性极强
- 编译阶段即可检查类型错误,避免运行时出现
ClassCastException - 使用时无需手动强制类型转换,代码更简洁安全
内容的提问来源于stack exchange,提问作者d1zyz
相关产品推荐
相关产品推荐

