【LinkedList demo 内部类讲说】

发布于:2025-05-25 ⋅ 阅读:(16) ⋅ 点赞:(0)

LinkedList demo 内部类讲说

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
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到