2つの配列要素JAVAとの比較(同一または異なる要素を識別するために)
より転載 https://blog.csdn.net/qq_35792598/article/details/76149552
図1に示すように、二つの配列において同一の要素を見つけます
public static Set<Integer> getIds(Integer[] a, Integer[] b){
Set<Integer> same = new HashSet<Integer>(); //用来存放两个数组中相同的元素 Set<Integer> temp = new HashSet<Integer>(); //用来存放数组a中的元素 for (int i = 0; i < a.length; i++) { temp.add(a[i]); //把数组a中的元素放到Set中,可以去除重复的元素 } for (int j = 0; j < b.length; j++) { //把数组b中的元素添加到temp中 //如果temp中已存在相同的元素,则temp.add(b[j])返回false if(!temp.add(b[j])) same.add(b[j]); } return same; } public static void main(String[] arg){ Integer[] array1 = {1,2,3,4,1,2,4,6,7,8,10,22,33}; Integer[] array2 = {1,2,3,4,1,2,4,6,7,8,10,22,33,55,66,77,88,99}; Set<Integer> sameElementSet = getIds(array1,array2); for(Integer i : sameElementSet) { System.out.println(i); } }
出力:
1
2
33
3
4
6
22
7
8
10
図2に示すように、二つの配列が同様の要素を識別していません
public static <T> List<T> compare(T[] t1, T[] t2) {
List<T> list1 = Arrays.asList(t1); //将t1数组转成list数组
List<T> list2 = new ArrayList<T>();//用来存放2个数组中不相同的元素 for (T t : t2) { if (!list1.contains(t)) { list2.add(t); } } return list2; } public static void main(String[] arg){ Integer[] array1 = {1, 2, 3}; Integer[] array2 = {1, 2, 3, 4,44}; List<Integer> list = compare(array1,array2); for (Integer integer : list) { System.out.println(integer); } }
出力:
4
44
サプリメント
比較二つの配列は同じ要素ではない、より横断し、次にトラバースの数に比べて少なくすべきです。
:のために(T Tマルチ){
IF {(以下.Contains(T)!)
、異なるセットが(t)を.add
}
}
:前記
多房セット
以下小さく設定されている
複数の組の要素tを
同じコレクションを入れていない要素の同じセットではありません