php英文商城网站建设,网站布局设计规则,html怎么做移动端网站,万能浏览器破解版文章目录 添加元素获取元素检查元素删除元素修改元素获取列表大小检查列表是否为空清空列表查找元素索引获取列表的子列表 List 是 Java 集合框架中的一个接口#xff0c;它表示一个有序的集合#xff08;序列#xff09;#xff0c;允许存储重复的元素。List 接口提供了许… 文章目录 添加元素获取元素检查元素删除元素修改元素获取列表大小检查列表是否为空清空列表查找元素索引获取列表的子列表 List 是 Java 集合框架中的一个接口它表示一个有序的集合序列允许存储重复的元素。List 接口提供了许多方法来操作列表中的元素。以下是一些常用的 List 方法及其示例 添加元素
add(E e)列表的末尾添加指定的元素。 add(int index, E element)在列表的指定位置插入指定的元素。
ListString list new ArrayList();
list.add(Apple); // 在末尾添加元素
list.add(1, Banana); // 在索引1的位置插入元素
System.out.println(list); // 输出: [Apple, Banana] 获取元素
get(int index)返回列表中指定位置的元素。
ListString list new ArrayList();
list.add(Apple);
list.add(Banana);
list.add(Cherry);
String fruit list.get(1); // 获取索引1的元素
System.out.println(fruit); // 输出: Banana 检查元素
contains(Object o)如果此列表包含指定的元素则返回 true。
ListString list new ArrayList();
list.add(Apple);
list.add(Banana);
boolean containsBanana list.contains(Banana);
System.out.println(containsBanana); // 输出: true 删除元素
remove(int index)除列表中指定位置的元素。 remove(Object o)移除列表中首次出现的指定元素。
ListString list new ArrayList();
list.add(Apple);
list.add(Banana);
list.add(Cherry);
list.remove(1); // 移除索引1的元素
System.out.println(list); // 输出: [Apple, Cherry] list.remove(Apple); // 移除元素Apple
System.out.println(list); // 输出: [Cherry] 修改元素
可以通过索引直接修改 List 中的元素因为 List 允许随机访问。
ListString list new ArrayList();
list.add(Apple);
list.add(Banana);
list.set(0, Orange); // 修改索引0的元素为Orange
System.out.println(list); // 输出: [Orange, Banana] 获取列表大小
size()返回列表中的元素数量。
ListString list new ArrayList();
list.add(Apple);
list.add(Banana);
int size list.size(); // 获取列表大小
System.out.println(size); // 输出: 2 检查列表是否为空
isEmpty()如果此列表不包含元素则返回 true。
ListString list new ArrayList();
boolean isEmpty list.isEmpty(); // 检查列表是否为空
System.out.println(isEmpty); // 输出: true list.add(Apple);
isEmpty list.isEmpty(); // 再次检查列表是否为空
System.out.println(isEmpty); // 输出: false 清空列表
clear()移除列表中的所有元素。
ListString list new ArrayList();
list.add(Apple);
list.add(Banana);
list.clear(); // 清空列表
System.out.println(list.isEmpty()); // 输出: true因为列表已被清空 查找元素索引
indexOf(Object o)返回此列表中首次出现的指定元素的索引如果此列表不包含该元素则返回 -1。 lastIndexOf(Object o)返回此列表中最后一次出现的指定元素的索引如果此列表不包含该元素则返回 -1。
ListString list new ArrayList();
list.add(Apple);
list.add(Banana);
list.add(Apple); int index list.indexOf(Apple); // 查找首次出现的Apple的索引
System.out.println(index); // 输出: 0 int lastIndex list.lastIndexOf(Apple); // 查找最后一次出现的Apple的索引
System.out.println(lastIndex); // 输出: 2 int notFoundIndex list.indexOf(Cherry); // 查找不存在的元素
System.out.println(notFoundIndex); // 输出: -1 获取列表的子列表
subList(int fromIndex, int toIndex)返回列表中指定的 fromIndex包括和 toIndex不包括之间的部分视图。
ListString list new ArrayList();
list.add(Apple);
list.add(Banana);
list.add(Cherry);
list.add(Date); ListString subList list.subList(1, 3); // 获取索引1到3不包含3的子列表
System.out.println(subList); // 输出: [Banana, Cherry]