Common functions of top-level interface Collection
Overview
Collection is the top-level interface of single-column collections, and the top-level interface of single-column collections defines the functions common to all single-column collections. JDK does not provide any direct implementation of this interface. He provides more specific sub-interfaces (such as Set and List) to achieve
Create Collection object
Collection interface, you cannot create objects directly, you need an implementation class ArrayList to create objects
1) Polymorphism: the way of polymorphism-the parent class reference points to the child class object Collection c = new ArrayList();
2) Specific implementation class creation-this class reference points to this class object ArrayList a = new ArrayList();
Collection collection commonly used methods:
1) boolean add (Object e): add elements
2) boolean remove (Object o): remove the specified element from the collection
3) void clear(): Clear the elements in the collection
4) boolean contains(Object o): Determine whether the specified element exists in the collection
5) boolean isEmpty(): Determine whether the collection is empty (the collection exists, there are no elements), if the collection is empty, then return true, if the collection is not empty false
6) int size(): Returns the number of elements in the collection, returns the length of the collection
7) Object[] toArray(): returns an array of objects of the collection
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);
}
}
}