java:Collection集合常用功能

java.util.Collection接口
作用:
所有单列集合最顶层的接口,里面定义了所有单列集合共性的方法
任意的单列集合都可以使用Collection接口中的方法
1.创建集合对象,使用多态

Collection<String> coll = new ArrayList<>();
coll.add("李四");
coll.add("胡歌");
coll.add("艾克");
coll.add("德玛");
System.out.println(coll);//[李四,胡歌,艾克,德玛]

2.public boolean add(E e):把给定的对象添加到当前集合中(返回值为boolean值)

boolean a = coll.add("张三");
System.out.println(a);//ture
System.out.println(coll);//[李四,胡歌,艾克,德玛,张三]

3.public boolean remove(E e):把给定的对象在当前集合中删除(返回值为boolean: 集合中存在元素,删除元素,返回ture ,集合中不存在则返回false)

//删除存在的元素李四
boolean b = cool.remove("李四");
System.out.println(b);//true
System.out.println(coll);//[胡歌,艾克,德玛,张三]
//删除不存在的元素迪迦
boolean c = cool.remove("迪迦");
System.out.println(c);//false
System.out.println(coll);//[李四,胡歌,艾克,德玛,张三]

4.public boolean contains(E e): 判断当前集合中是否包含给定的对象(包含返回true 不包含返回false)

//判断胡歌是否存在
Boolean d = cool.contains("胡歌");
System.out.println(d);//ture
//判断亚索是否存在
Boolean e = cool.contains("亚索");
System.out.println(e);//ture

5.public boolean isEmpty(): 判断当前集合是否为空

boolean f = coll.isEmpt();
System.out.println(f);//false

6.public boolean size(): 返回集合中元素的个数

boolean g = cool.size();
System.out.println(g);//4

7.public Object[] toArray(): 把集合中的元素,存储到数组中

//因为数组数据类型不同,所以要将它改为泛型Object[],它可以存储任意类型
Object[]arr = cool.toArray();
//使用否循环遍历元素 arr.length为集合长度
for(int i = 0;i < arr.length; i++){
	System.out.println(arr[i]);//胡歌,艾克,德玛,张三
}

8.public void clear(): 清空集合中所有元素,但不删除集合

cool.clear();
System.out.println(cool);//[]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值