JavaSE进阶-Collection
Collection集合概述与使用
概述
- Collection是个接口
- 是单例集合的顶层接口,它表示一组对象,这些对象也被称为Collection的元素
- JDK不支持Collection接口的直接实现,它提供了更具体的子接口(List和Set)的实现。
创建Collection集合的对象
- 多态的方式
- 具体的实现类ArrayList,ArrayList实现的是List接口,而List接口继承Collection接口,所以我们可以通过具体的实现类ArrayList来创建Collection集合的对象
基本使用
Colletion集合的常用方法
注:用父类的引用Collection c 去接收 子类的对象 new ArrayList<>();删除指定元素时,不能通过下标去删除
Collection集合的遍历
- Iteratoe:迭代器,集合的专用遍历方式,它是一个接口。
- Iterator iterator();返回集合中元素的迭代器。
- 迭代器是通过集合的iterator()方法得到的,所以我们说它是依赖于集合而存在的
Iterator的常用方法
- next():返回迭代中的下一个元素
- hasNext():如果迭代器具有更多元素,则返回true,一般是用来判断的
注:it.next();它只能获取下一个元素的值,并不能获取全部的元素,一旦获取到,迭代器就会指向下一个元素
Collection集合存储学生对象并遍历
源码:
package oopAdvance;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Scanner;
public class StudentTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//创建Collection集合
Collection<Student> c = new ArrayList<>();
System.out.println("录入学生个数:");
int sum = sc.nextInt();
for(int i=1;i<=sum;i++){
System.out.println("第"+i+"个学生:");
getStudent(c);
}
//遍历输出集合
//c.iterator().hasNext():用迭代器的方式判断集合是否有元素
java.util.Iterator<Student> it= c.iterator();
while(it.hasNext()){
Student s=it.next();
System.out.println(s);
}
}
public static void getStudent(Collection<Student> c){
Scanner sc = new Scanner(System.in);
System.out.println("请输入学生的姓名:");
String name = sc.nextLine();
System.out.println("请输入学生的年龄:");
String age = sc.nextLine();
//创建学生对象3
Student sutdent = new Student();
//将学生姓名、年龄存入对象中
sutdent.setName(name);
sutdent.setAge(age);
//将学生对象存入集合中
c.add(sutdent);
}
}