Collection体系集合
集合
概念:对象的容器,定义了对多个对象进行操作的常用方法。可实现数组的功能
和数组区别:
1.数组长度固定,集合长度不固定
2.数组可以存储基本类型和引用类型,集合只能存储引用类型
位置: java. util.*;
Collection体系集合
Collection(interface) 该体系结构得根接口,代表一组对象
1.List(interface) 特点:有序、有下标、元素可以重复
1)ArrayList(Class)
2)LinkedList(Class)
3)Vertor(Class)
2.Set(interface) 特点:无序、无下标、元素不能重复
1)HashSet(Class)
2)SortedSet(interface) TreeSett(Class)
Collection父接口
特点:代表一组任意类型的对象,无序、无下标、不能重复
方法:
boolean add (0bject obj) //添加一个对象
boolean addAll (Collection c) //将一个集合中的所有对象添加到此集合中
void clear() //清空此集合中的所有对象
boolean contains (Object o) //检查此集合中是否包含o对象
boolean equals (Object o) //比较此集合是否与指定对象相等
boolean isEmpty() //判断此集合是否为空
boolean remove (0bject o) //在此集合中移除o对象
int size() //返回此集合中的元素个数
0bject[] toArray() //将此集合转换成数组
eg :
public class Demo01 {
public static void main(String[] args) {
//创建集合
Collection collection = new ArrayList();
//(1)添加元素
collection.add ("苹果");
collection.add ("西瓜");
collection.add ("榴莲");
System.out.println ("元素个数:"+collection.size());
System.out.println(collection);
//(2)删除元素
//collection.remove("榴莲");
//collection.clear();
//System.out.println("删除之后:"+collection.size ());
//(3)遍历元素 重点
//3.1使用增强for
for (Object object : collection){
System.out.println(object);
}
//3.2使用迭代器(迭代器专门用来遍历集合的一种方式)
//hasNest();有没有下一个元素
//nest();获取下一个元素
//remove();删除当前元素
Iterator it = collection.iterator();
while(it.hasNext ( )){
String s = (String)it.next ();
System.out.println (s);
//collection.remove (s);
//it.remove ();
}
System.out.println("元素个数:"+collection.size ());
//(4)判断
System.out.println(collection.contains("西瓜"));
System.out.println(collection.isEmpty());//元素不为空false 反之true
}
}

浙公网安备 33010602011771号