11 集合
02 Collection集合常用功能
package Collection.Collection;
import java.util.ArrayList;
import java.util.Collection;
/*
java.util.collection接口
所有单列集合的最顶层的接口,里边定义了所有单列集合共性的方法任意的单列集合都可以使用Collection接口中的方法共性的方法:
public boolean add(E e):把给定的对象添加到当前集合中。
public void clear():清空集合中所有的元素。
public boolean remove(E e):把给定的对象在当前集合中删除。
public boolean contains(E e):判断当前集合中是否包含给定的对象。
public boolean isEmpty():判断当前集合是否为空。
public int size():返回集合中元素的个数。
-
public Object[]toArray():把集合中的元素,存储到数组中。
*/
public class Demo01 {
public static void main(String[] args) {
//创建集合对象,可以使用多态
Collection<String> coll = new ArrayList<>();
System.out.println(coll); //重写了toString方法 []
boolean b1 = coll.add("张三");
System.out.println(b1); //true
System.out.println(coll);
coll.add("李四");
coll.add("王五");
coll.add("赵六");
coll.add("田七");
System.out.println(coll);
/*
remove 删除的元素有返回true,不存在返回false
*/
boolean b2 = coll.remove("赵六");
System.out.println(b2);
boolean b3 = coll.remove("赵四");
System.out.println(b3);
System.out.println(coll);
//contains 判断是否包含给定的对象
boolean b4 = coll.contains("李四");
boolean b5 = coll.contains("赵四");
System.out.println(b4);
System.out.println(b5);
//isEmpty判断是否为空
boolean b6 = coll.isEmpty();
System.out.println(b6);
//size返回集合元素个数
int size = coll.size();
System.out.println(size);
//Object[] toArray(); 把集合中的元素,存储到数组中
Object[] arr = coll.toArray();
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
//clear 清空集合中的元素
coll.clear();
System.