要在链表中的第一个项目之前添加一个项目,我们使用LinkedList.addFisrt()方法,并在链表中的最后一个项目之后添加一个项目,我们使用LinkedList.addLast()方法。
package org.nhooo.example.util; import java.util.LinkedList; public class LinkedListAddItems { public static void main(String[] args) { LinkedList<String> grades = new LinkedList<>(); grades.add("B"); grades.add("C"); grades.add("D"); grades.add("E"); System.out.println("Original values are:"); System.out.println("===================="); for (String grade : grades) { System.out.println("Grade = " + grade); } grades.addFirst("A"); grades.addLast("F"); System.out.println("New values are:"); System.out.println("===================="); for (String grade : grades) { System.out.println("Grade = " + grade); } } }
该程序的结果如下:
Original values are: ==================== Grade = B Grade = C Grade = D Grade = E New values are: ==================== Grade = A Grade = B Grade = C Grade = D Grade = E Grade = F