欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > 【LinkedList demo 内部类讲说】

【LinkedList demo 内部类讲说】

2025/6/21 0:05:34 来源:https://blog.csdn.net/qq_39118371/article/details/148101117  浏览:    关键词:【LinkedList demo 内部类讲说】

LinkedList demo 内部类讲说

      • 1. Node节点
      • 2.MyLinkedList
      • 3. LinkedListTest 测试类

1. Node节点

public class Node<T> {private Node<T> pre;private Node<T> next;private T data;public Node() {}public Node getPre() {return pre;}public void setPre(Node pre) {this.pre = pre;}public Node getNext() {return next;}public void setNext(Node next) {this.next = next;}public T getData() {return data;}public void setData(T data) {this.data = data;}public Node(Node pre, Node next, T data) {this.pre = pre;this.next = next;this.data = data;}
}

2.MyLinkedList

public class MyLinkedList<T>{private Node<T> head;private Node<T> tail;private int size;public MyLinkedList() {}public MyLinkedList(Node<T> head) {this.head = head;}public void add(T data) {if (head == null) {Node<T> node = new Node<>();node.setData(data);head = node;tail = node;} else {Node<T> node = new Node<>();node.setData(data);node.setPre(tail);node.setNext(null);tail.setNext(node);tail = node;}size++;}public int size() {return size;}public T get(int index) {if (index < 0 || index >= size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);Node<T> node = head;for (int i = 0; i < index; i++) {node = node.getNext();}return (T)node.getData();}
}

3. LinkedListTest 测试类

public class LinkedListTest {/*** 内部类可以访问外部类的所有成员,包括私有成员。根据定义的位置分为:* 1.成员内部类(最常用)* 2.静态内部类* 3.局部内部类* 4.匿名内部类* 形象地比喻,内部类像是“遥控器的电池”* 想象一下,你买了一台空调,它配有一个遥控器(内部类)* 遥控器可以控制空调,就像内部类可以访问外部类的属性* 如果遥控器有电池仓(匿名内部类),可以插入具体电池(一个临时的实现)** 何时使用内部类?* 内部类只为外部类服务,不需要被外部调用* 需要访问外部类的私有成员时,* 代码结构上是一种强关联的逻辑组织。*/public static void main(String[] args) {MyLinkedList<String> list = new MyLinkedList<>();list.add("aa");list.add("bb");list.add("cc");String result = list.get(1);System.out.println(result); //输出bb}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词