一些常用的Collections的方法:
Collections.shuffle(集合名);这个是随机打乱某个集合中元素的顺序 也就是洗牌
Collections.addAll(集合名,元素1,元素2);这个就是一次性去添加多个元素
如下:
-
排序(Sorting):
sort(List<T> list)
: 对列表进行原位排序reverse(List<?> list)
: 反转指定列表中元素的顺序shuffle(List<?> list)
: 使用默认随机源对指定列表进行置换
-
查找和替换(Searching and Replacing):
binarySearch(List<? extends Comparable<? super T>> list, T key)
: 使用二分搜索算法搜索指定列表,以获得指定对象replaceAll(List<T> list, T oldVal, T newVal)
: 用新值替换指定列表中的所有旧值
-
线程安全集合(Synchronized Collections):
synchronizedCollection(Collection<T> c)
: 返回指定 collection 支持的同步(线程安全的) collectionsynchronizedList(List<T> list)
: 返回指定列表支持的同步(线程安全的)列表
-
不可修改集合(Immutable Collections):
unmodifiableCollection(Collection<? extends T> c)
: 返回指定 collection 的不可修改视图unmodifiableList(List<? extends T> list)
: 返回指定列表的不可修改视图
-
批操作(Bulk Operations):
addAll(Collection<? super T> c, T... elements)
: 将所有指定元素添加到指定 collection 中copy(List<? super T> dest, List<? extends T> src)
: 将所有元素从一个列表复制到另一个列表
-
最大、最小值(Max and Min):
max(Collection<? extends T> coll)
: 根据其自然顺序返回给定 collection 的最大元素min(Collection<? extends T> coll)
: 根据其自然顺序返回给定 collection 的最小元素
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Student> allStudents = new ArrayList<>();
Student temps = new Student();
int idCounter = 1; // 用于分配学生编号
while (true) {
System.out.println("学生管理系统————by XYC");
System.out.println("1.添加学生请输入1");
System.out.println("2.删除学生请输入2");
System.out.println("3.查找学生请输入3");
System.out.println("4.获取年龄最大学生请输入4");
System.out.println("5.随机打乱学生请输入5");
System.out.println("6.输出所有学生信息请输入6");
System.out.println("0.退出请输入0");
Scanner sc = new Scanner(System.in);
int select = sc.nextInt();
switch (select) {
case 1:
System.out.println("请输入学生姓名");
temps.setName(sc.next());
System.out.println("请输入学生的年龄");
temps.setAge(sc.nextInt());
temps.setId(idCounter);
idCounter++; // 学生编号递增
allStudents.add(temps);
System.out.println(temps + " 已经输入成功 编号为" + temps.getId());
break;
case 2:
System.out.println("请输入要删除学生的编号");
int deleteId = sc.nextInt();
boolean removed = false;
for (Student student : allStudents) {
if (student.getId() == deleteId) {
allStudents.remove(student);
removed = true;
System.out.println("删除成功");
break; // 找到匹配的学生并移除后直接跳出循环
}
}
if (!removed) {
System.out.println("未找到对应编号的学生");
}
break;
case 4:
System.out.println(Collections.max(allStudents, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge() - o2.getAge();
}
}));
case 5:
Collections.shuffle(allStudents);
case 6:
System.out.println(allStudents);
break;
case 0:
System.out.println("退出程序");
return; // 退出程序
}
}
}
}