举例分析:
两个数组a和b分别为 {1,2,3,4} {3,4,5,6}
- 交集:两个数组的相同元素{3,4}
- 并集:两个数组中所有的元素(包括重复的){1,2,3,4,3,4,5,6}
- 差集:两个数组中不想同的元素,例:a与b的差集{1,2}、b与a的差集{5,6}
此时用ArrayList的哪个方法来实现最为简单,是首要思考的问题。
- 交集是判断两个数组相同的元素,可以用ArrayList方法中的retainAll()方法:
敲黑板:看源码
public boolean retainAll(Collection<?> c) {
return batchRemove(c, true); //调用这个方法↓↓↓
}
//batch-批量的意思batchRemove就是批量删除
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData; //新建一个存储元素的数组
int r = 0, w = 0;
boolean modified = false; //用来判断是否被修改 (modified-被修改)
try {
for (; r < size; r++) //遍历数组
//如果c数组中包含下标r所对应的值,将这个值添加到新数组中
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
if (r != size) {
//arraycopy(Object src(源数组), int srcPos(原数组的起始位置,不一定是0号位置),Object dest(目的数组), int destPos(目的数组的起始位置), int length(拷贝的长度));
System.arraycopy(elementData, r,elementData, w,size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
- 并集:
求并集有两种方法:
①遍历a数组,直接把b数组的值一个个存进去
②使用addAll()方法:a.addAll(b) - 差集:
使用removeAll()方法;
代码实现:
public class ArrayListDemo218 {
public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList<Integer>();
ArrayList<Integer> b = new ArrayList<Integer>();
a.add(1);
a.add(2);
a.add(3);
a.add(4);
b.add(3);
b.add(4);
b.add(5);
b.add(6);
//并集
for (int k = 0; k < b.size(); k++) {//并集第一种方式
a.add(b.get(k));
}
//a.addAll(b);并集第二种方式
System.out.println("并集:");
for (int n = 0; n < a.size(); n++) {
System.out.print(a.get(n) + " ");
}
System.out.println( );
//交集
a.retainAll(b);
System.out.println("交集:");
for (int n = 0; n < a.size(); n++) {
System.out.print(a.get(n) + " ");
}
System.out.println( );
//差集
a.removeAll(b);
System.out.println("a与b的差集:");
for (int n = 0; n < a.size(); n++) {
System.out.print(a.get(n) + " ");
}
}
}
实现结果:
- 并集
- 交集
- 差集
集合源码中有很多很多方法,要记住几个常用的在需要的时候就不用自己再去实现啦,所以集合特别实用。