集合的概念:对象的容器,定义了对多个对象进行操作的常用方法。可实现数组的功能。
和数组的区别:
(1)数组长度固定,集合长度不固定
(2)数组可以存储基本类型和引用类型,集合只能存储引用类型
位置:java.util.*
Collection体系集合
是否有序:添加顺序和遍历顺序不同
有无下标:能否通过下标访问
Collection父接口
特点:代表一组任意类型的对象,无序、无下标、不能重复。
方法:
方法 | 说明 |
---|---|
boolean add(Object obj) | 添加一个对象 |
boolean addAll(Collection c) | 将一个集合中的所有对象添加此集合中 |
void clear() | 清空此集合的所有对象 |
boolean equals(Object o) | 比较此集合是否与指定对象相等 |
boolean isEmtpy() | 判断此集合是否为空 |
boolean remove(Object o) | 在集合中移除o对象 |
int size() | 返回此集合中的元素个数 |
Object[] toArray() | 将此集合转换成数组 |
public static void main(String[] args) {
/*
Collection接口的使用
(1)添加元素
(2)删除元素
(3)遍历元素
(4)判断元素
*/
//创建一个集合
Collection collection = new ArrayList();
//(1)添加元素
collection.add("apple");
collection.add("banana");
collection.add("peer");
System.out.println("Num:"+collection.size());
System.out.println(collection);
//(2)删除元素
collection.remove("banana");
//collection.clear();
System.out.println("Num:"+collection.size());
System.out.println(collection);
//(3)遍历元素
//3.1 增强for,不能使用普通for,无下标
for (Object obj:collection) {
System.out.println(obj);
}
System.out.println("===============");
//3.2 使用迭代器(专门用于遍历集合的一种方式)
//Iterator 也是接口
//hasNext();有无下一个元素
//next();获取下一个元素
//remove();删除当前元素
Iterator it= collection.iterator();
while(it.hasNext()){
String object = (String) it.next();
System.out.println(object);
//不能使用collection删除方法
//it.remove();
}
System.out.println("Num:"+collection.size());
//(4)判断元素
System.out.println(collection.contains("apple"));
}
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "[name:"+this.name+" age:"+this.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 static void main(String[] args) {
/*
Collection保存学生信息
*/
//新建Collection对象
Collection collection = new ArrayList();
Student s1 = new Student("A",10);
Student s2 = new Student("B",11);
Student s3 = new Student("C",12);
Student s4 = new Student("D",13);
//1.添加数据
collection.add(s1);
collection.add(s2);
collection.add(s3);
collection.add(s4);
System.out.println("Num:"+collection.size());
System.out.println(collection);
//2.删除
/*collection.remove(s2);
collection.remove(new Student("A",10));//不能删除s1,因为只是新建一个对象正好属性相同而已
System.out.println(collection);
System.out.println("删除后Num:"+collection.size());*/
//3.遍历
//3.1
for (Object obj:collection) {
Student s = (Student) obj;
System.out.println(s);
}
//3.2迭代器 hasNext();next();remove()
//迭代过程中不能使用collection的删除方法
System.out.println("=====迭代");
Iterator it = collection.iterator();
while (it.hasNext()){
Student ss = (Student) it.next();
System.out.println(ss);
}
//4.判断
System.out.println(collection.contains(s1));
System.out.println(collection.isEmpty());
}