本文共 3271 字,大约阅读时间需要 10 分钟。
集合是一种数据结构,用于存储多种类型的元素。与数组不同,集合可以包含不同的数据类型。集合在Java中通过Collection接口来实现,Collection是集合的父接口,所有集合容器都实现这个接口。
Collection接口定义了集合的基本操作,包括添加、删除、查找、清空等操作。常见的集合实现类有ArrayList、Vector、LinkedList等。ArrayList是最常用的集合容器,因为它在内存中表示为数组,操作速度较快。
迭代器是一种用于遍历集合元素的机制。通过调用iterator()方法可以获取集合的迭代器。迭代器提供了三种主要方法:hasNext()、next()和remove()。这些方法允许我们逐个访问和操作集合中的元素。
List接口是Collection接口的子接口之一,它代表一系列有序的集合容器。与Set接口不同,List允许元素重复,并且提供了随机访问元素的索引功能。常见的List实现类有ArrayList和LinkedList。
ArrayList的优势LinkedList的优势使用普通的迭代器进行集合操作时,可能会导致ConcurrentModificationException异常。这是因为迭代器和集合同时进行修改会导致并发修改。为了避免这种问题,可以使用ListIterator,它允许在遍历集合的同时进行修改操作。
Set接口允许存储唯一的元素,不能重复。Set集合不保证存储和访问顺序一致。常见的Set实现类有HashSet、TreeSet等。
HashSet基于哈希表实现,查询速度非常快。要存储自定义对象,需要实现equals()和hashCode()方法。
TreeSet基于二叉搜索树实现,元素存储顺序由自然顺序决定。可以通过自定义比较器来指定排序规则。
import java.util.HashSet;import java.util.Set;class Student { private String name; private int age; Student(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return this.name + ":" + this.age; } @Override public int hashCode() { return this.age; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Student other = (Student) obj; return this.name.equals(other.name) && this.age == other.age; }}public class Main { public static void main(String[] args) { Set students = new HashSet<>(); students.add(new Student("张三", 25)); students.add(new Student("李四", 21)); students.add(new Student("王五", 25)); students.add(new Student("赵六", 24)); students.add(new Student("陈七", 25)); for (Student student : students) { System.out.println(student); } }} import java.util.TreeSet;import java.util.Comparator;class Student implements Comparable { private String name; private int age; Student(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return this.name + ":" + this.age; } @Override public int compareTo(Object o) { Student other = (Student) o; if (this.age > other.age) return 1; if (this.age < other.age) return -1; return 0; }}class ComparatorByName implements Comparator { @Override public int compare(Student o1, Student o2) { int result = o1.getName().compareTo(o2.getName()); return result == 0 ? o1.getAge() - o2.getAge() : result; }}public class Main { public static void main(String[] args) { TreeSet students = new TreeSet<>(new ComparatorByName()); students.add(new Student("张三", 25)); students.add(new Student("李四", 21)); students.add(new Student("王五", 25)); students.add(new Student("赵六", 24)); students.add(new Student("陈七", 25)); for (Student student : students) { System.out.println(student); } }} 通过以上示例,可以看出集合在Java中的重要性以及它们在不同场景下的应用。集合提供了灵活的数据存储和操作功能,是Java开发中常用的工具。
转载地址:http://ngfh.baihongyu.com/