顶层接口Collection常用功能
概述
Collection是单列集合的顶层接口,单列集合的顶层接口,定义的是所有单列集合中共有的功能。JDK不提供此接口的任何直接实现。他提供更具体的子接口(如Set和List)实现
创建Collection集合的对象
Collection接口,不能直接创建对象,需要一个实现类ArrayList创建对象
1)多态:多态的方式–父类引用指向子类对象 Collection c = new ArrayList();
2)具体的实现类创建 – 本类引用指向本类对象 ArrayList a = new ArrayList();
Collection集合常用方法:
1)boolean add(Object e):添加元素
2)boolean remove (Object o): 从集合中移除指定的元素
3) void clear(): 清空集合中的元素
4 ) boolean contains(Object o): 判断集合中是否存在指定的元素
5 ) boolean isEmpty(): 判断集合是否为空(集合存在,没有元素), 如果集合为空, 那么返回true, 如果集合不为空 false
6 ) int size(): 返回集合中元素的数量,返回集合的长度
7 ) Object[] toArray(): 返回集合的对象的数组
package com.ujiuye.collection;
import java.util.ArrayList;
import java.util.Collection;
public class Demo01_Collection常用方法 {
public static void main(String[] args) {
// 1. 创建出一个集合
Collection c = new ArrayList();
// 2. boolean add(Object e): 添加元素
c.add("a");
c.add("hello");
c.add("b");
System.out.println(c);// [a, hello, b]
// 4. boolean contains(Object o): 判断集合中是否存在指定的元素
System.out.println(c.contains("hello"));// true
System.out.println(c.contains("he"));// false
// 5.boolean isEmpty(): 判断集合是否为空(集合存在,没有元素), 如果集合为空, 那么返回true, 如果集合不为空 false
System.out.println(c.isEmpty());// false
// 3. boolean remove (Object o): 从集合中移除指定的元素
c.remove("a");
System.out.println(c);// [hello, b]
//6. int size(): 返回集合中元素的数量,返回集合的长度。
System.out.println(c.size());// 2
// 4. void clear(): 清空集合中的元素
c.clear();
System.out.println(c);// []
// boolean isEmpty(): 判断集合是否为空(集合存在,没有元素), 如果集合为空, 那么返回true, 如果集合不为空 false
System.out.println(c.isEmpty());// true
//6. int size(): 返回集合中元素的数量,返回集合的长度。
System.out.println(c.size());// 0
System.out.println("-------------------");
// 7. Object[] toArray(): 返回集合的对象的数组
Object[] objArr = c.toArray();
// 通过遍历数组相当于在遍历集合中元素内容
for(int index = 0; index < objArr.length; index++){
Object obj = objArr[index];
String s = (String)obj;
System.out.println(s);
}
}
}