Java 集合简介、遍历集合(迭代器方式)
1、集合简介
集合的特点:提供一种存储空间可变的存储模型,存储的数据容量可以随时发生改变
集合的体系结构
1.1、Collection集合概述和使用
Collection集合概述
- 是单列集合的顶层接口,它表示一组对象,这些 对象也称Collection的元素
- JDK不提供此接口的任何直接实现,它提供更具体的子接口(如set和List)实现
创建Collection集合的对象
- 多态的方式
- 具体的实现类ArrayList
1.2、Collection集合常用方法
方法名 | 说明 |
---|---|
boolean add(E e) | 添加元素 |
boolean remove(Object o) | 从集合中移除指定的元素 |
void clear() | 清空集合中的元素 |
boolean contains(Object o) | 判断集合中是否存在指定的元素 |
boolean isEmpty() | 判断集合是否为空 |
int size() | 集合的长度,也就是集合中元素的个数 |
1.3、Coolection集合的遍历
lterator:迭代器,集合的专用遍历方式
- lterator< E > iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到
- 迭代器是通过集合的iterator()方法得到的,所以我们说它是依赖于集合而存在的
Iterator中的常用方法
- E next():返回迭代器中的下一个元素
- boolean hasNext():如果迭代器具有更多元素,则返回true
遍历集合(迭代器方式)题目
需求:
创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合
思路:
1、定义学生类
2、创建Collection集合对象
3、创建学生对象
4、把学生添加到集合
5、遍历集合(迭代器方式)
定义学生类源代码
public class student {
private String name;
private int age;
public student(){
}
public student(String name,int age){
this.name=name;
this.age=age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age){
this.age=age;
}
public int getAge(){
return age;
}
}
测试类源代码
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class collectionDemo {
public static void main(String[] args) {
//创建Collection集合对象
Collection<student> c=new ArrayList<student>();
//创建学生对象
student a1=new student("俊杰",21);
student a2=new student("小玲",20);
//把学生添加到集合
c.add(a1);
c.add(a2);
//遍历集合(迭代器方式)
Iterator<student> it= c.iterator();
while (it.hasNext()){
student s=it.next();
System.out.println(s.getName()+","+s.getAge());
}
}
}