Collection接口概述
Collection 层次结构中的根接口。Collection 表示一组对象,这些对象也称为 collection 的元素。一些 collection 允许有重复的元素,而另一些则不允许。一些 collection 是有序的,而另一些则是无序的。
boolean add(E e)
boolean remove(Object o)
void clear()
boolean contains(Object o)
boolean isEmpty()
int size()
下面写一个测试类来测试上面的方法
package cn.itcast_01; import java.util.ArrayList; import java.util.Collection;
public class CollectionDemo {
public static void main(String[] args) {
// 测试不带All的方法
// 创建集合对象
// Collection c = new Collection(); //错误,因为接口不能实例化
Collection c = new ArrayList();
// boolean add(Object obj):添加一个元素
// System.out.println("add:"+c.add("hello"));
c.add("hello");
c.add("world");
c.add("java");
// void clear():移除所有元素
// c.clear();
// boolean remove(Object o):移除一个元素
// System.out.println("remove:" + c.remove("hello"));
// System.out.println("remove:" + c.remove("javaee"));(删除原来集合没有的元素,返回False,集合的元素不变,对原集合没有影响)
// boolean contains(Object o):判断集合中是否包含指定的元素
// System.out.println("contains:"+c.contains("hello"));
// System.out.println("contains:"+c.contains("android"));
// boolean isEmpty():判断集合是否为空
// System.out.println("isEmpty:"+c.isEmpty());
//int size():元素的个数
System.out.println("size:"+c.size());
System.out.println("c:" + c);
}
}用记事本练习,编译的时候会报下面这样一个问题
注意:collectionXxx.java使用了未经检查或不安全的操作.
注意:要了解详细信息,请使用 -Xlint:unchecked重新编译.(这不是编译失败,又不是报错!知识可能报错!)
java编译器认为该程序存在安全隐患
温馨提示:这不是编译失败,所以先不用理会,等学了泛型你就知道了
ArrayList这个集合放元素永远都可以成功(因为它的Add源码最后一句是return true),所以可以说 ArrayList这个集合是个可重复的集合
增删方法直接动集合,判断不动集合
本文出自 “GD” 博客,转载请与作者联系!
原文地址:http://wangdenghui.blog.51cto.com/9930072/1768415