JavaSE——集合(二)Collection接口

JavaSE——集合(二)Collection接口

Collection接口方法

  1. add()
Collection c=new ArrayList();
//add(Object e)
c.add("AA");
c.add("BB");
c.add(123);
c.add(new Date());
  1. size()
//size()获取已经有的元素数量
System.out.println(c.size());
  1. addAll()
//addAll()将另一个集合元素添加进去
Collection c1=new ArrayList();
c1.add("CC");
c1.add(456);
c1.add(new String("Tom"));
c1.add(new People("Harry",20));
c.addAll(c1);
System.out.println(c.toString());
  1. isEmpty()
//isEmpty():判断当前集合是否有元素
System.out.println(c.isEmpty());//false
  1. clear()
//clear():清空集合元素
c.clear();
  1. contains()
//contains():调用的equals()
System.out.println(c.contains("CC"));
System.out.println(c.contains(new String("Tom")));//这里是true,
System.out.println(c.contains(new People("Harry",20)));//true 自定义类需要重写equals
// 因为调用的是equals函数,在String里面已经重写过了是用来比较内容的。
  1. conainsAll()
//conainsAll()
Collection c2= Arrays.asList(123,456);
System.out.println(c.containsAll(c2));//true
  1. remove()
//remove()
System.out.println(c.remove(123));//true 因为在删除之前需要判断是否存在,所以也需要重写equals方法
  1. removeAll()
//removeAll():移除两个集合当中共有的,差集操作,修改了原集合
c.removeAll(c2);
System.out.println(c);
  1. retainAll()
//retainAll:求交集,同样修改了原集合
System.out.println(c);
c.retainAll(c2);
System.out.println(c);
  1. equals(Object obj)
//equals(Object obj):当前集合和形参集合元素相同,注意顺序
  1. hashCode()
//hashCode():返回当前对象的hash值
System.out.println(c.hashCode());//487
  1. toArray()
//toArray():集合转换为数组
Object[] arr=c.toArray();
		for(int i=0;i<arr.length;++i){
				System.out.print(arr[i]+" ");
		}
System.out.println("");
  1. Arrays.asList()
//Arrays.asList():数组到集合
List<String> l1=Arrays.asList(new String[]{"AA","BB"});//[AA, BB]
List<Integer> l2=Arrays.asList(new Integer[]{1,2});//[1, 2]
List<int[]> l3=Arrays.asList(new int[]{1,2});//[[I@45ee12a7]注意如果不适用包装类的话,会把元素当作一个地址值处理
System.out.println(l1);
System.out.println(l2);
System.out.println(l3);
  1. iterator()
//iterator():返回迭代器接口,用于遍历集合的元素
Iterator it = c.iterator();
while(it.hasNext()){
		System.out.println(it.next());
		}
}
Iterator it = c.iterator();
while(it.hasNext()){
    Object e=it.next();
    if(e.equals("Tom")) it.remove();
}
it=c.iterator();
while (it.hasNext()) System.out.println(it.next());

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值