Java集合<3> (Collection)

本文详细介绍了Java集合框架中Collection接口的使用方法,包括常见的List和Set子接口,并讲解了如何进行添加、删除、判断元素存在及迭代操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Collection子接口

Collection 接口也是java集合类中一个父类接口,Collection 子接口常用的有List,Set等。。。

因为List与Set的子类都会实现Collection接口,因此我们可以通过统一的迭代操作:

public static void doSomething(Collection collection){
    Iterator iterator = collection.iterator();
    while(iterator.hasNext()){
        Object obj = iterator.next();
        // do somethong with obj here
    }   
}

集合的添加和删除

不管集合子类内部如何实现添加和删除操作,我们只需要简单调用add()与remove()方法即可

String element = "an element";
Collection collection = new HashSet();
boolean added = collection.add(element);
boolean removed = collection.remove(element);

除了添加和删除单个元素外,Collection接口中还有添加和删除一个集合的操作:

Set set = new HashSet();
List list = new ArrayList();
Collection collection = new HashSet();
collection.addAll(set);
collection.addAll(list);
collection.removeAll(set);
collection.removeAll(list);

判断元素或集合是否存在与集合中

Collection collection = new HashSet();
boolean contained = collection.contains("an element");

Collection elements = new HashSet();
boolean containedAll = collection.containsAll(elements);

获取集合中元素数量

int numberOfElements = collection.size();

迭代操作

// iterator方式
Collection collection = new HashSet();
//... add elements to the collection

Iterator iterator = collection.iterator();
while(iterator.hasNext()){
    Object object = iterator.next();
    //do something to object;    
}

// for-loop方式
Collection collection = new HashSet();
//... add elements to the collection

for(Object object : collection) {
  //do something to object;
}

转载于:https://my.oschina.net/kevinair/blog/190847

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值