import java.util.LinkedList;
public class ArrayTest {
/**
* @param args
*/
public static void main(String[] args) {
String[] str1={"aa","bb","cc","dd","cd"};
String[] str2={"ab","cd","bb","mm"};
System.out.println("---------------交集------------------");
String[] intersect_result=intersect(str1,str2);
for (String str : intersect_result) {
System.out.print(str+",");
}
System.out.println("");
System.out.println("---------------差集------------------");
String[] chaSet_result=chaSet(str1,str2);
for (String str : chaSet_result) {
System.out.print(str+",");
}
System.out.println("");
System.out.println("---------------并集------------------");
String[] bingSet_result=bingSet(str1,str2);
for (String str : bingSet_result) {
System.out.print(str+",");
}
}
//求两个数组的交集
public static String[] intersect(String[] arr1, String[] arr2) {
LinkedList<String> newL = new LinkedList<String>();
LinkedList<String> history = new LinkedList<String>();
String[] longerArr = arr1;
String[] shorterArr = arr2;
//找出较长的数组来减较短的数组
if (arr1.length > arr2.length) {
longerArr = arr1;
shorterArr = arr2;
}
for (String str : longerArr) {
if (!history.contains(str)) {
history.add(str);
}
}
for (String str : shorterArr) {
if (history.contains(str)) {
newL.add(str);
history.remove(str);
} else {
history.remove(str);
}
}
String[] result = {};
return newL.toArray(result);
}
//求两个数组的差集
public static String[] chaSet(String[] arr1, String[] arr2) {
LinkedList<String> newL = new LinkedList<String>();
LinkedList<String> history = new LinkedList<String>();
String[] longerArr = arr1;
String[] shorterArr = arr2;
//找出较长的数组来减较短的数组
if (arr1.length > arr2.length) {
longerArr = arr1;
shorterArr = arr2;
}
for (String str : longerArr) {
if (!history.contains(str)) {
history.add(str);
}
}
for (String str : shorterArr) {
if (history.contains(str)) {
history.remove(str);
} else {
newL.add(str);
history.remove(str);
}
}
for(String str : history){
newL.add(str);
}
String[] result = {};
return newL.toArray(result);
}
//求两个数组的并集
public static String[] bingSet(String[] arr1, String[] arr2) {
LinkedList<String> newL = new LinkedList<String>();
LinkedList<String> history = new LinkedList<String>();
String[] longerArr = arr1;
String[] shorterArr = arr2;
//找出较长的数组来减较短的数组
if (arr1.length > arr2.length) {
longerArr = arr1;
shorterArr = arr2;
}
for (String str : longerArr) {
if (!history.contains(str)) {
history.add(str);
}
}
for (String str : shorterArr) {
if (!history.contains(str)) {
history.add(str);
}
}
String[] result = {};
return history.toArray(result);
}
}
浙公网安备 33010602011771号