Java学习-集合框架
什么是集合
对象的容器,定义了对多个对象进行操作的方法,可实现数组的功能。
和数组的区别:
1.数组长度固定,集合长度可变
2.数组可以存储基本类型和引用类型,集合只能存储引用类型
Collection体系集合
List接口:有序、有下标、元素可重复,ArrayList、LinkedList、Vector
Set接口:无序、无下标、元素不能重复,HashSet、SortedSet、TreeSet
Collection父接口
代表一组任意类型的对象,无序、无下标、不能重复
1.boolean add(Object obj):添加一个对象
2.boolean addAll(Collection c):添加集合中的所有对象
3.void clear():清空所有对象
4.boolean contains(Object o):检查是否包含此对象
5.boolean equals(Object o):比较是否与此对象相等
6.boolean isEmpty():判断是否为空
7.boolean remove(Object o):移除对象
8.int size():返回集合中元素个数
9.Object[] toArray():将集合转为数组
案例1:
Collection collection = new ArrayList();
collection.add("苹果");
collection.add("西瓜");
collection.add("榴莲");
sout(collection.size());//→ 3
sout(collection)//→ [苹果,西瓜,榴莲]
collection.remove("苹果");
sout(collection.size());//→ 2
collection.clear();
sout(collection.size());//→ 0
for(Object object:collection){sout(object);}//→ 苹果 \n 西瓜 \n 榴莲
Iterator it = collection.iterator();
// hasNext()、next()、remove()
while(it.hasNext()){
String s = (String)it.next();
sout(s);
//collection.remove(s);//→ ConcurrentModificationException,不能使用 collection 的 remove()
//it.remove(s);//可以使用 it 的 remove()
}//→ 苹果 \n 西瓜 \n 榴
sout(collection.contains("西瓜"));//→ true
sout(collection.isEmpty());//→ false
案例2:
public class Student{
private String name;
private int age;
//有参构造、无参构造、get、set、toString
}
public class Demo{
public static void main(String[] args){
Collection collection = new ArrayList();
Student s1 = new Student("张三",20);
Student s2 = new Student("李四",21);
collection.add(s1);
collection.add(s2);
sout(collection.seze());//→ 2
sout(collection.toString());//→ [Student[name=张三,age=20],Student[name=李四,age=21]]
collection.remove(s1);
collection.remove(new Student("张三",20));//→ 不能删除
sout(collection.seze());//→ 1
for(Object object:collection){Sutdent s = (Student)object;sout(s.toString());}
//→ Student[name=张三,age=20]] \n Student[name=李四,age=21]]
Iterator it = collection.iteartor;
while(it.hasNext()){Sutdent s = (Student)object;sout(s.toString());}
//→ Student[name=张三,age=20]] \n Student[name=李四,age=21]]
collection.contains(s1);//→ true
collection.contains(new Student("张三",20));//→ false
collection.clear();
}
}