Java 实例 - 数组交集

以下实例演示了如何使用 retainAll () 方法来计算两个数组的交集:

Main.java 文件

  1. import java.util.ArrayList;
  2. public class Main {
  3. public static void main(String[] args) {
  4. ArrayList objArray = new ArrayList();
  5. ArrayList objArray2 = new ArrayList();
  6. objArray2.add(0,"common1");
  7. objArray2.add(1,"common2");
  8. objArray2.add(2,"notcommon");
  9. objArray2.add(3,"notcommon1");
  10. objArray.add(0,"common1");
  11. objArray.add(1,"common2");
  12. objArray.add(2,"notcommon2");
  13. System.out.println("array1 数组元素:"+objArray);
  14. System.out.println("array2 数组元素:"+objArray2);
  15. objArray.retainAll(objArray2);
  16. System.out.println("array2 & array1 数组交集为:"+objArray);
  17. }
  18. }

以上代码运行输出结果为:

  1. array1 数组元素:[common1, common2, notcommon2]
  2. array2 数组元素:[common1, common2, notcommon, notcommon1]
  3. array2 & array1 数组交集为:[common1, common2]