Collection集合常用方法

java.util.Collection接口: 所有单列集合的最顶层接口,里边定义了所有单列集合共性的方法, 任意的单列集合都可以使用Collection接口中的方法
共性方法:
boolean add(E e); 向集合中添加元素
boolean remove(E e); 删除集合中的某个元素
void clear(); 清空集合中的所有元素
boolean contains(E e); 判断集合中是否包含某个元素
boolean isEmpty(); 判断集合是否为空
int size(); 获取集合的长度
Object[] toArray(); 将集合转换成一个数组

public class Demo01Collection {
	public static void main(String[] args) {
		//创建一个集合对象,可以使用多态
		Collection<String> coll = new ArrayList<>();
		//Collection<String> coll = new HashSet<>();效果是一样的
		System.out.println(coll);//[],说明重写了toString方法
		
		//public boolean add(E e); 向集合中添加元素
		//返回值是一个boolean值,一般都返回true,所以可以不用接收
		boolean b1 = coll.add("张三");
		System.out.println("b1: " + b1);//b1: true
		System.out.println(coll);//[张三]
		coll.add("李四");
		coll.add("赵六");
		coll.add("田七");
		System.out.println(coll);//[张三, 李四, 赵六, 田七]
		
		//public boolean remove(E e); 删除集合中的某个元素
		//返回值是一个boolean值,集合中存在元素,删除元素,返回true;集合中不存在元素!,删除失败,返回false。
		boolean b2 = coll.remove("赵六");
		System.out.println("b2: " + b2);//b2: true
		boolean b3 = coll.remove("赵四");
		System.out.println("b3: " + b3);//b3: false
		System.out.println(coll);//[张三, 李四, 田七]
		
		//public boolean contains(E e); 判断集合中是否包含某个元素
		//包含返回true;不包含返回false
		boolean b4 = coll.contains("李四");
		System.out.println("b4: " + b4);//b4: true
		boolean b5 = coll.contains("赵四");
		System.out.println("b5: " + b5);//b5: false
		
		//public boolean isEmpty(); 判断集合是否为空
		//集合为空,返回true;集合不为空返回false。
		boolean b6 = coll.isEmpty();
		System.out.println("b6: " + b6);
		//public int size(); 获取集合的长度
		System.out.println("size;" + coll.size());//size;
		
		//public Object[] toArray(); 将集合转换成一个数组
		Object[] arr = coll.toArray();
		for (int i = 0; i < arr.length; i++) {
		System.out.println(arr[i]);
		}
		
		//public void clear(); 清空集合中的所有元素,但是不删除集合
		coll.clear();
		System.out.println(coll);//[]
		System.out.println(coll.isEmpty());//true
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值