230. Java 集合 – 操作集合本身的方法
前面我们讲过了处理单个元素和多个元素的方法。
目前来看一看:怎么直接操作集合本身!
主要涉及三种核心操作:
| 方法 | 功能 | 返回值类型 |
|---|---|---|
size() |
返回集合中元素的数量 | int |
isEmpty() |
判断集合是否为空 | boolean |
clear() |
清空集合中所有元素 | void |
1. 🔍 size() —— 获取集合中的元素数量
-
size()方法返回集合中当前元素的个数,返回类型是int。 - 常用于判断集合是否达到某种规模、或者遍历前的预检查等场景。
2. 🧹 isEmpty() —— 判断集合是否为空
-
isEmpty()方法返回一个 布尔值,告知你集合是不是空的。 - 内部实则就是判断
size() == 0。
🛠️ 示例:使用 size() 和 isEmpty()
import java.util.*;
public class SizeAndIsEmptyExample {
public static void main(String[] args) {
Collection<String> strings = new ArrayList<>();
strings.add("one");
strings.add("two");
if (!strings.isEmpty()) {
System.out.println("Indeed, strings is not empty!");
}
System.out.println("The number of elements in strings is " + strings.size());
}
}
🖨️ 输出结果:
Indeed, strings is not empty!
The number of elements in strings is 2
3. 🚀 clear() —— 清空集合
-
clear()方法直接把集合中的所有元素都移除,集合变为空。 - 调用之后,
size()会变成 0,isEmpty()会返回 true。
🛠️ 示例:使用 clear()
import java.util.*;
public class ClearExample {
public static void main(String[] args) {
Collection<String> strings = new ArrayList<>();
strings.add("one");
strings.add("two");
System.out.println("The number of elements in strings is " + strings.size());
strings.clear(); // 清空集合!
System.out.println("After clearing it, the number of elements is now " + strings.size());
}
}
🖨️ 输出结果:
The number of elements in strings is 2
After clearing it, the number of elements is now 0
🎤 总结
| 方法 | 用途 | 示例 |
|---|---|---|
size() |
获取集合元素数量 | list.size() |
isEmpty() |
检查集合是否为空 | list.isEmpty() |
clear() |
清空集合元素 | list.clear() |
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...


