集合
一、概述
集合类的特点:提供一种存储空间可变的存储模型,存储的容量可以随时发生改变。
集合分为单列集合接口Collection和双列集合接口Map,Collection分为可以存储重复数据的List接口和不可以存储重复数据的Set接口,List接口有ArraryList实现类、LinkedList实现类等,Set接口有HashSet实现类、TreeSet实现类等,Map接口有HashMap实现类等。
二、Collection集合概述和使用
概述:Collection是单列集合的顶层接口,它表示一组对象,这些对象也称为Collection的元素;JDK不提供此接口的任何直接实现,但是提供更具体的子接口(如Set和List)实现。
创建Collection集合的对象:
- 多态的方式
- 具体的实现类ArrayList
三、Collection集合常用方法
1.boolean add(E e):添加元素
2.boolean remove(Object o):从集合中移除指定的元素
3.void clear(e):清空集合中的元素
4.boolean contains(Object o):判断集合中是否存在指定的元素
5.boolean isEmpty():判断集合是否为空
6.int size():集合的长度(集合中元素的个数)
四、Collection集合的遍历
Iterator:迭代器,集合的专用遍历方式
- Iterator<E> iterator():返回此集合中元素的迭代器,通过集合的iterator()方法得到
- 迭代器是通过iterator()方法得到的,所以它依赖于集合而存在的
Iterator中常用方法
- E next():返回迭代中的下一个元素
- boolean hasNext():如果迭代具有更多元素,则返回true
五、集合的使用步骤
1.创建集合对象
2.添加元素
3.遍历集合
六、案例
1.需求
创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合。
2.思路
1)定义学生类
2)创建Collection集合对象
3)创建学生对象
4)把学生添加到集合
5)遍历集合(迭代器实现)
3.代码实现
学生类:
package CollectionStudy;
public 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;
}
}
测试类:
package CollectionStudy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Demo {
public static void main(String[] args) {
//创建集合类
Collection<Student> c = new ArrayList<Student>();
//创建学生对象
Student s1 = new Student(3,"qwe");
Student s2 = new Student(4,"asd");
Student s3 = new Student();
s3.setAge(5);
s3.setName("zxc");
//添加对象
c.add(s1);
c.add(s2);
c.add(s3);
//遍历
Iterator<Student> it = c.iterator();
while (it.hasNext()){
Student s = it.next();
System.out.println(s.getName()+","+s.getAge());
}
}
}