免费网站打包,wordpress登入页面,wd ex4 安装wordpress,橘子建站是什么示例1#xff1a;使用ArrayList创建并操作列表
ArrayList是List接口最常用的实现之一#xff0c;它内部使用数组来存储元素#xff0c;因此对于随机访问具有很高的效率。但是#xff0c;当涉及到频繁的插入或删除操作时#xff0c;它的性能可能会受到影响#xff0c;因为…示例1使用ArrayList创建并操作列表
ArrayList是List接口最常用的实现之一它内部使用数组来存储元素因此对于随机访问具有很高的效率。但是当涉及到频繁的插入或删除操作时它的性能可能会受到影响因为这些操作可能需要移动大量元素以保持索引的一致性。
import java.util.ArrayList;
import java.util.List;public class ArrayListExample {public static void main(String[] args) {// 创建一个ArrayList实例ListString 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实现了List接口并且基于双向链表的数据结构。这意味着它可以高效地进行插入和删除操作尤其是在列表的两端。然而对于随机访问而言LinkedList的表现不如ArrayList好因为它必须从头或尾开始遍历节点直到目标位置。
import java.util.LinkedList;
import java.util.List;public class LinkedListExample {public static void main(String[] args) {// 创建一个LinkedList实例ListString queue new LinkedList();// 向列表两端添加元素((LinkedListString) queue).addFirst(first);((LinkedListString) queue).addLast(last);// 从列表两端移除元素System.out.println(Removed from front: ((LinkedListString) queue).removeFirst());System.out.println(Removed from back: ((LinkedListString) queue).removeLast());// 在任意位置插入元素queue.add(0, middle);// 遍历列表for (String item : queue) {System.out.println(item);}}
}
示例3使用List.of()创建不可变列表
引入了一个新的静态工厂方法List.of()用于快速创建固定内容的不可变列表。这种方法非常适合于那些不需要改变的集合因为它提供了一种简洁的方式来定义常量集合而且由于它是不可变的所以更加安全。
import java.util.List;public class ImmutableListExample {public static void main(String[] args) {// 使用List.of()创建一个不可变列表ListString immutableList List.of(red, green, blue);// 尝试修改列表会抛出UnsupportedOperationException异常try {immutableList.add(yellow); // 这行代码将导致运行时错误} catch (UnsupportedOperationException e) {System.out.println(Cannot modify an immutable list.);}// 安全地读取列表内容for (String color : immutableList) {System.out.println(color);}}
}