Collection(单列集合)
其中,List系列集合:添加的元素是有序、可重复、有索引的。Set系列集合:无序、不重复、无索引
注意:使用List系列的contains()方法的时候,如果集合中存储的是自定义对象,一定要重写equals方法。这是因为contains()底层是使用equals方法进行判断,而在自定义对象中,equals()方法直接比较地址值。
Collection的遍历方式:迭代器遍历、增强for遍历、Lambda表达式遍历
1、迭代器遍历
演示代码:
public class demo1 {
public static void main(String[] args) {
Student s1 = new Student(18,"fox");
Student s2 = new Student(19,"joy");
Student s3 = new Student(20,"cxq");
ArrayList<Student> arr = new ArrayList<>();
arr.add(s1);
arr.add(s2);
arr.add(s3);
//获取迭代器对象,可以理解为指针
Iterator<Student> it = arr.listIterator();
//循环判断当前容器是否有数据
while(it.hasNext()){
//获取当前数据赋值给新的对象
Student next = it.next();
System.out.println(next.toString());
}
}
}
class Student{
private int age;
private String name;
public Student() {
}
public Student(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
演示结果:
注意点:
(1)迭代器遍历完,指针不会复位,如果想要重新遍历,需要申请一个新的迭代器
(2)循环中只能使用一次next方法,因为获取完当前数据,指针会自动往后移,如果多使用一次可能会导致指针指向空白处导致报错NoSuchElementException
(3)迭代器遍历时,不能用List集合方法进行增加或删除;如果想要进行删除,应该使用迭代器Iterator的remove()方法
2、增强for遍历
适用范围:所有的单列集合和数组才能用增强for进行遍历
3、Lambda表达式遍历
代码实现:
public class demo1 {
public static void main(String[] args) {
Student s1 = new Student(18,"fox");
Student s2 = new Student(19,"joy");
Student s3 = new Student(20,"cxq");
ArrayList<Student> arr = new ArrayList<>();
arr.add(s1);
arr.add(s2);
arr.add(s3);
//底层原理:自行遍历集合,获取每一个元素并传递给重写的accept方法
arr.forEach(new Consumer<Student>() {
@Override
public void accept(Student student) {
System.out.println(student.toString());
}
});
//也可以写成简化版的lambda表达式
arr.forEach(student -> System.out.println(student.toString()));
}
}
class Student{
private int age;
private String name;
public Student() {
}
public Student(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}