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()
把集合中的元素存储到数组中
实例代码:
import java.util.ArrayList; import java.util.Collection; public class Demo01Collection { public static void main(String[] args) { //创建集合对象,可以使用多态 Collection<String> coll = new ArrayList<>(); System.out.println(coll); /* public boolean add(E e) 把给定的对象添加到当前集合 返回值是布尔类型 */ boolean b1 = coll.add("迪丽热巴"); System.out.println("b1:"+b1); System.out.println(coll); coll.add("古力娜扎"); coll.add("马尔扎哈"); coll.add("撒由那拉"); /* public boolean remove(E e) 把给定的对象在当前集合中删除 返回值类型为布尔类型 若集合中存在给定对象,则删除,返回true 若集合中不存在给定给定对象,则删除失败,返回false */ boolean b2 = coll.remove("撒由那拉"); System.out.println("b2:"+b2); System.out.println(coll); /* public boolean containns(E e) 判断当前集合中是否包含给定的对象 返回值类型为布尔类型 若集合中存在给定对象,返回true 若集合中不存在给定给定对象,返回false */ boolean b3 = coll.contains("撒由那拉"); System.out.println("b3:"+b3); boolean b4 = coll.contains("迪丽热巴"); System.out.println("b4"+b4); //public boolean isEmpty() 判断当前集合是否为空 boolean b5 = coll.isEmpty(); System.out.println("b5"+b5); //public int size() 返回集合中元素的个数 int size = coll.size(); System.out.println("size:"+size); //public Object[] toArray() 把集合中的元素存储到数组中 Object[] obj = coll.toArray(); for (int i = 0; i < obj.length; i++) { System.out.println(obj[i]); } //public void clear() 清空集合中的所有对象 coll.clear(); System.out.println(coll); } }
结果如下:
今天好累,就学了一点的内容,但还是发现前面遗忘的真的是很多,抽时间要重头再看一遍了。
还是不熟悉,多做吧!