一、集合:
面向对象语言对事物的描述时通过对象实现的,为了方便对多个对象进行操作,就必须把这多个对象进行存储,要想存储多个对象,就应该用一个容器类型的变量,这个容器就是集合。
二、数组和集合的区别:
(1)长度:
数组长度确定
集合长度可变
(2)内容:
数组存储的是同一类型的元素
集合可以存储不同类型的元素
(3)元素的数据类型:
数组可以存储基本数据类型,也可以存储引用类型
集合只能存储引用类型
三、Connection:
是集合的顶层接口,它的子体系有重复的,有唯一的,有唯一的,有无序的。
1、Connection的功能概述:
(1)添加功能:
boolean add(E e):添加一个元素
boolean addAll(Collection<? extends E> c):添加一个集合的所有元素
(2)删除功能:
void clear():移除该集合中的所有元素
boolean remove(Object o):从集合中移除一个指定元素
boolean removeAll(Collection<?> c):移除一个集合的所有元素
(3)判断功能:
boolean contains(Object o):判断是否包含一个指定的元素
boolean containsAll(Collection<?> c):判断是否包含一个指定集合的全部元素
boolean isEmpty():判断集合是否为空
(4)获取功能:
Iterator<E> iterator():迭代器,遍历集合的一种方式
(5)长度功能:
int size():获取集合中的元素数
(6)交集功能:
boolean retainAll(Collection<?> c):仅保留集合中也包含指定集合的元素
假设有A,B两个集合,A对B做交集,结果保存在A中,B不变,但绘制表示的是
A是否发生过改变
(7)把集合转换成数组:
Object[] toArray()
用iterator()遍历集合:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
class Student{
String name;
int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class CollectionDemo {
public static void main(String[] args) {
Collection c = new ArrayList();
Student s = new Student("A",3);
Student s1 = new Student("B",4);
Student s2 = new Student("C",5);
Student s3 = new Student("D",6);
Student s4 = new Student("E",7);
c.add(s);
c.add(s1);
c.add(s2);
c.add(s3);
c.add(s4);
Iterator i = c.iterator();
while(i.hasNext()) {
Student stu = (Student)i.next();
System.out.println(stu.name+"---"+stu.age);
}
}
}
四、集合的使用步骤:
1、创建几何对象
2、创建元素对象
3、把元素添加到集合
4、遍历集合:
通过集合对象获取迭代器对象
通过迭代器对象的hasNext()方法判断是否有元素
通过迭代器对象的next()方法获取元素并移动到下一个位置