鼠標放到一級導航時才顯示網(wǎng)站二級導航 鼠標離開時不顯示 怎么控制站長統(tǒng)計app軟件
示例1:使用ArrayList
創(chuàng)建并操作列表
ArrayList
是List
接口最常用的實現(xiàn)之一,它內(nèi)部使用數(shù)組來存儲元素,因此對于隨機訪問具有很高的效率。但是,當涉及到頻繁的插入或刪除操作時,它的性能可能會受到影響,因為這些操作可能需要移動大量元素以保持索引的一致性。
import java.util.ArrayList;
import java.util.List;public class ArrayListExample {public static void main(String[] args) {// 創(chuàng)建一個ArrayList實例List<String> names = new ArrayList<>();// 添加元素到列表names.add("Alice");names.add("Bob");names.add("Charlie");// 修改指定位置的元素names.set(1, "Bobby");// 獲取指定位置的元素System.out.println("The second name is: " + names.get(1));// 刪除指定位置的元素String removedName = names.remove(2);System.out.println("Removed name: " + removedName);// 遍歷列表for (String name : names) {System.out.println(name);}// 輸出列表大小System.out.println("Size of list: " + names.size());}
}
示例2:使用LinkedList
處理頻繁的插入與刪除
LinkedList
實現(xiàn)了List
接口,并且基于雙向鏈表的數(shù)據(jù)結構。這意味著它可以高效地進行插入和刪除操作,尤其是在列表的兩端。然而,對于隨機訪問而言,LinkedList
的表現(xiàn)不如ArrayList
好,因為它必須從頭或尾開始遍歷節(jié)點直到目標位置。
import java.util.LinkedList;
import java.util.List;public class LinkedListExample {public static void main(String[] args) {// 創(chuàng)建一個LinkedList實例List<String> queue = new LinkedList<>();// 向列表兩端添加元素((LinkedList<String>) queue).addFirst("first");((LinkedList<String>) queue).addLast("last");// 從列表兩端移除元素System.out.println("Removed from front: " + ((LinkedList<String>) queue).removeFirst());System.out.println("Removed from back: " + ((LinkedList<String>) queue).removeLast());// 在任意位置插入元素queue.add(0, "middle");// 遍歷列表for (String item : queue) {System.out.println(item);}}
}
示例3:使用List.of()
創(chuàng)建不可變列表
引入了一個新的靜態(tài)工廠方法List.of()
,用于快速創(chuàng)建固定內(nèi)容的不可變列表。這種方法非常適合于那些不需要改變的集合,因為它提供了一種簡潔的方式來定義常量集合,而且由于它是不可變的,所以更加安全。
import java.util.List;public class ImmutableListExample {public static void main(String[] args) {// 使用List.of()創(chuàng)建一個不可變列表List<String> immutableList = List.of("red", "green", "blue");// 嘗試修改列表會拋出UnsupportedOperationException異常try {immutableList.add("yellow"); // 這行代碼將導致運行時錯誤} catch (UnsupportedOperationException e) {System.out.println("Cannot modify an immutable list.");}// 安全地讀取列表內(nèi)容for (String color : immutableList) {System.out.println(color);}}
}