方法一:利用集合的contains方法,建立臨時集合組裝數據去重數組
public void listTest1(){ System.out.println("方法一"); List<Integer> list = new ArrayList<Integer>(); for (int i=0;i<=2;i++){ for (int j=0;j<=3;j++){ list.add(j); } } //建立一個臨時集合裝去重後的數據 List<Integer> tempList = new ArrayList<Integer>(); for(Integer i : list){ if(!tempList.contains(i)){//判斷是否有重複數據,若是沒有就將數據裝進臨時集合 tempList.add(i); } } System.out.println("去重前"); for (Integer i:list){ System.out.print(i+" "); } System.out.println(); System.out.println("去重後"); for (Integer i:tempList){ System.out.print(i+" "); } }
方法二:經過Iterator 的remove方法函數
public void listTest2(){ System.out.println("方法二"); List<Integer> list = new ArrayList<Integer>(); for (int i=0;i<=2;i++){ for (int j=0;j<=3;j++){ list.add(j); } } System.out.println("去重前"); for (Integer i:list){ System.out.print(i+" "); } //建立一個臨時集合裝去重後的數據 List<Integer> tempList = new ArrayList<Integer>(); Iterator<Integer> iter = list.iterator(); while(iter.hasNext()){ int t=iter.next(); if(tempList.contains(t)){ iter.remove(); } else{ tempList.add(t); } } System.out.println(); System.out.println("去重後"); for (Integer i:list){ System.out.print(i+" "); } }
方法一:傳入一個Object數組,而後返回去重後的數組spa
public Object[] arrayTest1(Object[] arr){ //用來記錄去除重複以後的數組長度和給臨時數組做爲下標索引
int t = 0;
Object[] tempArr = new Object[arr.length];
for(int i = 0; i < arr.length; i++){ //聲明一個標記,並每次重置
boolean isTrue = true;
for(int j=i+1;j<arr.length;j++){ //若是有重複元素,改變標記狀態並結束當次內層循環
if(arr[i]==arr[j]){ isTrue = false; break; } } //判斷標記是否被改變,若是沒被改變就是沒有重複元素
if(isTrue){
tempArr[t] = arr[i]; //到這裏證實當前元素沒有重複,那麼記錄自增
t++; } } //聲明須要返回的數組,這個纔是去重後的數組
Object[] newArr = new Object[t]; //用arraycopy方法將剛纔去重的數組拷貝到新數組並返回
System.arraycopy(tempArr,0,newArr,0,t); return newArr; }
方法二:利用hashset去重code
public Object[] arrayTest2(Object [] arr){ //實例化一個set集合
Set set = new HashSet(); //遍歷數組並存入集合,若是元素已存在則不會重複存入
for (int i = 0; i < arr.length; i++) { set.add(arr[i]); } //返回Set集合的數組形式
return set.toArray(); }
main方法blog
public static void main(String args[]){ ArrayAndListRemove remove = new ArrayAndListRemove(); System.out.println("集合去重"); remove.listTest1(); remove.listTest2(); System.out.println("數組去重"); Object[] arr = {0,1,2,3,0,1,2,3,0,1,2,3}; System.out.println("去重前"); for (int i=0;i<arr.length;i++){ System.out.println(arr[i]+" "); } System.out.println("去重後"); Object[] arr1 = remove.arrayTest1(arr); for (int i=0;i<arr1.length;i++){ System.out.print(arr1[i]+" "); } System.out.println(); Object[] arr2 = remove.arrayTest2(arr); for (int i=0;i<arr2.length;i++){ System.out.print(arr2[i]+" "); } }
控制檯打印結果索引
注意:public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) src:源數組; srcPos:源數組要複製的起始位置; dest:目的數組; destPos:目的數組放置的起始位置; length:複製的長度。src and dest都必須是同類型或者能夠進行轉換類型的數組. 有趣的是這個函數能夠實現本身到本身複製rem