package note;
import java.util.ArrayList;
import java.util.List;
/***
* 集合运算: 1、并集(or) 2、交集(and) 3、差集(not) 4、无重复的并集
* */
public class SetOperation {
// 并集
public static ArrayList get_orSet(ArrayList dataList1, ArrayList dataList2) {
ArrayList dataListCopy1 = new ArrayList();
dataListCopy1 = (ArrayList) dataList1.clone();
ArrayList dataListCopy2 = new ArrayList();
dataListCopy2 = (ArrayList) dataList2.clone();
dataListCopy1.addAll(dataListCopy2);
return dataListCopy1;
}
// 交集
public static ArrayList get_andSet(ArrayList dataList1, ArrayList dataList2) {
ArrayList dataListCopy1 = new ArrayList();
dataListCopy1 = (ArrayList) dataList1.clone();
ArrayList dataListCopy2 = new ArrayList();
dataListCopy2 = (ArrayList) dataList2.clone();
// retainAll方法会删除dataListCopy1中没有出现在dataListCopy2中的元素
dataListCopy1.retainAll(dataListCopy2);
return dataListCopy1;
}
// 差集
public static ArrayList get_notSet(ArrayList dataList1, ArrayList dataList2) {
ArrayList dataListCopy1 = new ArrayList();
dataListCopy1 = (ArrayList) dataList1.clone();
ArrayList dataListCopy2 = new ArrayList();
dataListCopy2 = (ArrayList) dataList2.clone();
dataListCopy1.removeAll(dataListCopy2);
return dataListCopy1;
}
// 无重复并集(注意:不能用HashSet实现)
public static ArrayList get_onlyorSet(ArrayList dataList1,
ArrayList dataList2) {
ArrayList dataListCopy1 = new ArrayList();
dataListCopy1 = (ArrayList) dataList1.clone();
ArrayList dataListCopy2 = new ArrayList();
dataListCopy2 = (ArrayList) dataList2.clone();
dataListCopy2.removeAll(dataListCopy1);
dataListCopy1.add(dataListCopy2);
return dataListCopy1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList dataList1 = new ArrayList();
ArrayList dataList2 = new ArrayList();
dataList1.add(1);
dataList1.add(8);
dataList1.add(3);
dataList1.add(4);
dataList1.add(4);
dataList1.add(3);
dataList2.add(1);
dataList2.add(3);
dataList2.add(4);
dataList2.add(5);
dataList2.add(6);
dataList2.add(5);
dataList2.add(2);
List bingji, jiaoji, chaji, wuchongfu_bingji;
bingji = SetOperation.get_orSet(dataList1, dataList2);
jiaoji = SetOperation.get_andSet(dataList1, dataList2);
chaji = SetOperation.get_notSet(dataList1, dataList2);
wuchongfu_bingji = SetOperation.get_onlyorSet(dataList1, dataList2);
// 原集合1
System.out.println("原集合1:" + dataList1);
// 原集合2
System.out.println("原集合2:" + dataList2);
// 并集
System.out.println("并集:" + bingji);
// 交集
System.out.println("交集:" + jiaoji);
// 差集
System.out.println("差集:" + chaji);
// 无重复并集
System.out.print("无重复并集:" + wuchongfu_bingji);
}
}
错误处,请指出,谢谢!
阅读(997) | 评论(0) | 转发(0) |