開始使用免費開始

操作 LinkedList

現在你要用 LinkedList(相對於 ArrayList)建立一個購物清單,並在清單上進行與之前相同的 String 物件新增與移除。這能讓你看到 LinkedListArrayList 共享相同的 List 介面,且在行為上具有多型性。

本練習屬於課程

Java 的資料型別與例外狀況

檢視課程

練習說明

  • 匯入 LinkedList 以供此應用程式使用。
  • 建立一個新的 String 型別 LinkedList,並指定給變數 shopList
  • "eggs" 加到購物清單的尾端。
  • 將第二個 "milk" 加到購物清單的開頭。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

// Import LinkedList
import java.____.____;

public class Shopping {

	public static void main(String[] args) {

		// Create a LinkedList of Strings using parameterized constructor
		____<____> shopList = ____ ____<____>();
		shopList.addLast("milk");
        // Add eggs to the end of the list
		shopList.____("____");
		shopList.addLast("bread");
		// Add milk to the beginning of the list again
		shopList.____("____");
		System.out.println(shopList);
		shopList.set(3,"rye-bread");
		shopList.remove("milk");
		System.out.println(shopList);
		System.out.println(shopList.size());
	}
}
編輯並執行程式碼