对一个数组去重
用list实现复杂度为O(n的平方)
public static List getDistinctArray(Integer[] a){
List arraySame = new ArrayList();
arraySame.add(a[0]);
boolean flag;
for(int i=1;i
用Set实现复杂度为O(n)
String[] array = {"a","b","c","c","d","e","e","e","a"};
Set set = new HashSet<>();
for(int i=0;i
比较两个数组相同与差异
package com.fei.maintest;
import java.util.*;
public class SetTest {
public static void main(String[] args) {
Integer[] array1 = {1,2,3,4,1,2,4,6,7,8,30,22,33};
Integer[] array2 = {1,2,3,4,1,2,4,6,7,8,30,22,33,55,66,77};
Set sameElementSet = getSameBySet(array1,array2);
System.out.println("\ngetSame by Set:");
for(Integer i : sameElementSet)
System.out.print(i+",");
List sameElementList = getSameByArray(array1,array2);
System.out.println("\ngetSame by List:");
for (int i=0;i list = compare(array1,array2);
System.out.println("\narray2 compare array1:");
for (Integer integer : list)
System.out.print(integer+",");
}
public static List getSameByArray(Integer[] a, Integer[] b){
List listA = getDistinctArray(a);
List listB = getDistinctArray(b);
List arraySame = new ArrayList();
for(int i=0;i getSameBySet(Integer[] a, Integer[] b){
Set same = new HashSet(); //用来存放两个数组中相同的元素
Set temp = new HashSet(); //用来存放数组a中的元素
for (int i = 0; i < a.length; i++) {
temp.add(a[i]); //把数组a中的元素放到Set中,可以去除重复的元素
}
System.out.println("temp:");
Iterator it = temp.iterator();
while (it.hasNext()) {
System.out.print(it.next()+",");
}
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 List compare(T[] t1, T[] t2) {
List list1 = Arrays.asList(t1);
List list2 = new ArrayList();
for (T t : t2) {
if (!list1.contains(t)) {
list2.add(t);
}
}
return list2;
}
public static List getDistinctArray(Integer[] a){
List arraySame = new ArrayList();
arraySame.add(a[0]);
boolean flag;
for(int i=1;i
输出
temp:
1,33,2,3,4,6,22,7,8,30,
getSame by Set:
1,33,2,3,4,6,22,7,8,30,
getSame by List:
1,2,3,4,6,7,8,30,22,33,
array2 compare array1:
55,66,77,
如果传入的两个数组有重复
package com.fei.maintest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class ReadfileTest {
public static void main(String[] args) {
String fileName = "/Users/bestfei/Downloads/url.txt";
String fileNameB = "/Users/bestfei/Downloads/url2.txt";
//readFileByLines(fileName);
List a = getFileArrayListByLines(fileName);
List b = getFileArrayListByLines(fileNameB);
System.out.println("getSameBySet");
getSameBySet(getDistinctSet(a),getDistinctSet(b));
System.out.println("getSameByArrayList");
getSameByArrayList(getDistinctArrayList(a),getDistinctArrayList(b));
}
public static void getSameByArrayList(List a,List b){
ArrayList l = new ArrayList();
for(int i=0;i
参考文档:
http://blog.csdn.net/xiaoxiaopengbo/article/details/51583386
http://blog.csdn.net/qq_33642117/article/details/52040345