Java 简明教程

Java LinkedList Class

Introduction

Java LinkedList 类的操作会执行我们对双向链表的预期操作。对列表进行索引的操作将从开头或结尾遍历列表,以更接近指定索引的一端为准。

The Java LinkedList class operations perform we can expect for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.

Class declaration

下面是 java.util.LinkedList 类的声明 −

Following is the declaration for java.util.LinkedList class −

public class LinkedList<E>
   extends AbstractSequentialList<E>
   implements List<E>, Deque<E>, Cloneable, Serializable

Parameters

以下是 java.util.LinkedList 类的参数 −

Following is the parameter for java.util.LinkedList class −

E − 这是此集合中保留元素的类型。

E − This is the type of elements held in this collection.

Field

从类 java.util.AbstractList 继承的字段。

Fields inherited from class java.util.AbstractList.

Class constructors

Class methods

Methods inherited

此类从以下类中继承方法:

This class inherits methods from the following classes −

  1. java.util.AbstractSequentialList

  2. java.util.AbstractList

  3. java.util.AbstractCollection

  4. java.util.Object

  5. java.util.List

  6. java.util.Deque

Adding element to a LinkedList Example

以下示例展示了 Java LinkedList add(E) 方法的使用,用它来添加整数。我们通过对每个元素使用 add() 方法调用将两个整数添加到 LinkedList 对象,然后打印每个元素以显示添加的元素。

The following example shows the usage of Java LinkedList add(E) method to add Integers. We’re adding couple of Integers to the LinkedList object using add() method calls per element and then print each element to show the elements added.

package com.tutorialspoint;

import java.util.LinkedList;

public class LinkedListDemo {
   public static void main(String[] args) {

      // create an empty linked list
      LinkedList<Integer> linkedList = new LinkedList<>();

      // use add() method to add elements in the linkedList
      linkedList.add(20);
      linkedList.add(30);
      linkedList.add(20);
      linkedList.add(30);
      linkedList.add(15);
      linkedList.add(22);
      linkedList.add(11);

      // let us print all the elements available in linkedList
      for (Integer number : linkedList) {
         System.out.println("Number = " + number);
      }
   }
}

Output

让我们编译并运行上述程序,这将生成以下结果 −

Let us compile and run the above program, this will produce the following result −

Number = 20
Number = 30
Number = 20
Number = 30
Number = 15
Number = 22
Number = 11