228. Java 集合 - 操作集合中的单个元素
1. 🎯 基本操作:添加和删除元素
在集合(Collection)中,我们最基本的两项操作是:
| 方法 | 作用 | 返回值 |
|---|---|---|
add(element) | 将元素添加到集合中 | 返回true表示添加成功,false表示失败 |
remove(element) | 将指定元素从集合中移除 | 返回true表示移除成功,false表示失败 |
📌 注意:
- 在
List中,add()几乎总是成功的(因为允许重复元素)。 - 在
Set中,add()可能失败(因为不允许重复元素)。
2. 🛠️ 示例:使用 ArrayList 添加和删除元素
import java.util.*;
public class CollectionExample {
public static void main(String[] args) {
// 创建一个存储 String 的集合
Collection<String> strings = new ArrayList<>();
// 添加元素
strings.add("one");
strings.add("two");
System.out.println("strings = " + strings);
// 删除元素
strings.remove("one");
System.out.println("strings = " + strings);
}
}
🖨️ 输出结果:
strings = [one, two]
strings = [two]
3. 🔎 检查元素是否存在:contains()
想要检查集合中是否包含某个元素?可以使用contains()方法!
| 方法 | 作用 |
|---|---|
contains(element) | 检查集合中是否存在指定元素,返回true或false |
📌 小提示:
虽然集合是有泛型类型的(比如这里是String),但**contains()允许你传任何对象进去**进行检测!
比如你可以在一个存放String的集合里,检查一个User对象是否存在。
(当然,这通常没什么意义,只是Java语言设计允许这么做。)
🛠️ 示例:使用 contains() 方法
import java.util.*;
class User {
private String name;
public User(String name) {
this.name = name;
}
}
public class ContainsExample {
public static void main(String[] args) {
Collection<String> strings = new ArrayList<>();
strings.add("one");
strings.add("two");
if (strings.contains("one")) {
System.out.println("one is here");
}
if (!strings.contains("three")) {
System.out.println("three is not here");
}
User rebecca = new User("Rebecca");
if (!strings.contains(rebecca)) {
System.out.println("Rebecca is not here");
}
}
}
🖨️ 输出结果:
one is here
three is not here
Rebecca is not here
4. 📢 IDE警告小知识
如果你用的是IDE(如 IntelliJ IDEA 或 Eclipse),当你用contains()检查一个不同类型的对象时(如检查User对象是否存在于String集合中),IDE通常会给你一个警告,提醒你类型不匹配。
虽然编译器允许,但这通常是一个潜在的逻辑错误,应当避免!
🎤 总结
add()➡️ 往集合中添加元素。remove()➡️ 从集合中移除元素。contains()➡️ 检查元素是否存在。- List允许重复元素,Set不允许重复元素。
- 注意类型匹配,避免用contains检查错误类型!