Java中集合retainall_Collection中的之retainAll()方法的理解

//在jdkapi中的方法,说明返回值为boolean类型,

boolean retainAll(Collection> c) ;

//api中给的注释

//Retains only the elements in this list that are contained in the specified collection

//只保留在此集合中存在的元素,

//A.retainAll(B),A调用这个方法之后,集合A中只剩下存在于B中的元素,返回值为false表示集合A没改变,返

回true集合A发生改变

//jdk中实现的源码

Boolean removeAll(Collection> c)

public boolean retainAll(Collection> c) { //返回值是否发生改变

return batchRemove(c, true);

}

private boolean batchRemove(Collection> c, boolean complement) {

final Object[] elementData = this.elementData;

int r = 0, w = 0;

boolean modified = false;

try {

for (; r < size; r++)

if (c.contains(elementData[r]) == complement)

elementData[w++] = elementData[r];

} finally {

// Preserve behavioral compatibility with AbstractCollection,

// even if c.contains() throws.

if (r != size) {

System.arraycopy(elementData, r,

elementData, w,

size - r);

w += size - r;

}

if (w != size) {

for (int i = w; i < size; i++)

elementData[i] = null;

modCount += size - w;

size = w;

modified = true;

}

}

return modified;

}

example:

public class collection_test {

public static void main(String args[]) {

Collection c=new ArrayList();

Collection c1=new ArrayList(); c.add("a1"); c.add("a2");

c1.add("a3"); c1.add("a1"); c1.add("a2");

System.out.println(c.retainAll(c1)); System.out.println(c.toString()); System.out.println(c1.toString());

} }

结果: false [a1, a2] [a3, a1, a2]

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值