public class CompareArray {
public static void main(String[] args) {
String[] a = {"a","b","c"};
String[] b = {"a","b","c","d"};
System.out.println(compareArray(a, b));
System.out.println(compareArray(b, a));
/**
* 找出a数组中不在b数组中的值
*/
String[] notInArray = notInArray(b,a);
if(notInArray != null && notInArray.length > 0){
for(int i = 0; i < notInArray.length; i ++){
System.out.println(notInArray[i]);
}
}
String[] c = {"a","d"};
String[] d = {"a","e","f"};
/**
* 找出的是d中不在c中的字符串,输出,e/f
*/
String[] notInArray2 = notInArray(c,d);
if(notInArray2 != null && notInArray2.length > 0){
for(int i = 0; i < notInArray2.length; i ++){
System.out.println(notInArray2[i]);
}
}
/**
* 实际业务场景
* 找出新选择的人员不在已发送的人员中的人
*/
String[] n = {"1","2","3"};
String[] o = {"1","4","5"};
String[] notInArray3 = notInArray(o, n);
if(notInArray3 != null && notInArray3.length > 0){
for (String string : notInArray3) {
System.out.println(string);
}
}
}
/**
* 比较两个数组是否相等
* @param arr1
* @param arr2
* @return
*/
public static boolean compareArray(String[] arr1, String[] arr2){
if(arr1 == arr2){
return true;
}
if(arr1.length > 0 && arr2.length > 0 && arr1.length == arr2.length){
Map<String,Object> map = new HashMap<String, Object>();
boolean flag = true;
for(int i = 0; i < arr1.length; i ++){
map.put(arr1[i], i);
}
for(int i = 0; i < arr2.length; i ++){
if(!map.containsKey(arr2[i])){
flag = false;
break;
}
}
return flag;
}
return false;
}
/**
* 找出arr2中不在arr1中的字符串
* @param arr1 key
* @param arr2
* @return
*/
public static String[] notInArray(String[] arr1,String[] arr2){
String[] res = null;
if(arr1 != arr2 && arr1.length > 0 && arr2.length > 0){
Map<String,Object> map = new HashMap<String, Object>();
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr1.length; i ++){
map.put(arr1[i], i);
}
for(int i = 0; i < arr2.length; i ++){
if(!map.containsKey(arr2[i])){
list.add(arr2[i]);
}
}
if(list.size() > 0){
res = new String[list.size()];
list.toArray(res);
return res;
}
}
return res;
}
}