在Java中,集合(Collections)是存储多个对象的容器。Java的集合框架(Java Collections Framework)提供了一套丰富的接口和类来实现各种集合结构。以下是一些简单的Java集合运用的示例:
1. 使用ArrayList存储整数
ArrayList是List接口的一个常用实现,它可以动态地增长和缩小。
import java.util.ArrayList;
import java.util.List;
public class ArrayListExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
for (int number : numbers) {
System.out.println(number);
}
}
}
2. 使用HashSet存储字符串
HashSet是一个不允许有重复元素的集合。
import java.util.HashSet;
import java.util.Set;
public class HashSetExample {
public static void main(String[] args) {
Set<String> colors = new HashSet<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
colors.add("Red"); // 这个元素不会被添加,因为HashSet不允许重复
for (String color : colors) {
System.out.println(color);
}
}
}
3. 使用HashMap存储键值对
HashMap是一个存储键值对的集合,它允许你通过键来快速查找、更新或删除值。
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
ages.put("Charlie", 35);
for (Map.Entry<String, Integer> entry : ages.entrySet()) {
System.out.println("Name: " + entry.getKey() + ", Age: " + entry.getValue());
}
}
}
4. 使用LinkedHashSet保持插入顺序
LinkedHashSet是HashSet的一个子类,它使用链表来维护元素的插入顺序。
import java.util.LinkedHashSet;
import java.util.Set;
public class LinkedHashSetExample {
public static void main(String[] args) {
Set<String> fruits = new LinkedHashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
一个比较简单的运用:
题目要求:
仔细阅读下面编辑区内给出的代码框架及注释,在 Begin-End 间编写程序代码,使用 HashSet 的常用方法完成所给要求,具体如下:
- 接收给定的一行字符串(如:hello,hi,ask);
- 根据英文逗号切割字符串,把切割后的元素添加进 HashSet;
- 判断集合中元素个数,当个数大于 4,且集合中没有元素 hello 时,往集合中添加元素 hello,如果集合中已有元素 hello,请输出提示语句:“集合中已有该元素”,当个数小于等于 4 时,请输出提示语句:“元素个数小于4”;
- 打印集合。
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String[] elements = input.split(",");
Set<String> set = new HashSet<>();
for (String element : elements) {
set.add(element);
}
if (set.size() > 4) {
if (set.contains("hello")) {
System.out.println("集合中已有该元素");
} else {
set.add("hello");
}
} else {
System.out.println("元素个数小于4");
}
System.out.println(set);
}
}