Collection 常用功能
Collection是所有单列集合的父接口,因此在Collection中定义了单列集合(List和Set)通用的一些方法,这些方法可用于操作所有的单列集合。
方法如下:
●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() : 把集合中的元素,存储到数组中。
API中的方法摘要:
示例代码(注意看注解):
import java.util.Collection;
import java.util.ArrayList;
public class CollectionClass {
public static void main(String[] args) {
//创建集合对象,可以使用多态
Collection<String> coll = new ArrayList<>();
System.out.println(coll); //覆盖重写了toString方法
//使用add方法,把对象添加到当前集合中,返回值为Boolean值
//一般为true,表示是否添加成功
boolean b1 = coll.add("张三");
System.out.println("b1:" + b1);
System.out.println(coll);
coll.add("李四");
coll.add("李五");
coll.add("李六");
System.out.println(coll);
//rermove 方法 ,把给定对象从当前结合总删除怒,返回boolean值
//表示是否删除成功
boolean b2 = coll.remove("李四");
System.out.println("b2:"+ b2);
System.out.println(coll);
//contain方法,判断当前集合中是否包含给定的对象
//返回值为boolean值
boolean b3 = coll.contains("李五");
System.out.println("b3:" + b3);
//isEmpty方法,判断当前集合是否为空
boolean b4 = coll.isEmpty();
System.out.println("b4:" + b4);
//size() 返回集合中元素的个数
int size = coll.size();
System.out.println("size:"+ size);
//toArray 把集合中的元素,存储到数组中
Object[] arr = coll.toArray();
for(int i = 0; i<arr.length;i++) {
System.out.println(arr[i]);
}
//clear() 清空集合中所有的元素,但是不删除集合,集合还在
coll.clear();
System.out.println(coll);
}
}
————————————————————————————
版权所有,转载请说明出处