Java array deduplication methods

// The first way: beginning conceivable use of non-repeatability of the set of filter elements Set
 public static Object [] oneClear (Object [] ARR) {
  Set new new SET = HashSet ();
  for (int I = 0; I <arr.length; I ++) {
    set.add (ARR [I]);
   }
  return set.toArray ();
 }

// second way: To maintain the original order on the use of sequential array, a linked list of features is not repeated hash set
 public static Object [] twoClear (Object [] ARR) {
  TEMP a LinkedHashSet a LinkedHashSet new new = <Object> < > ();
  for (int I = 0; I <arr.length; I ++) {
     temp.add (ARR [I]);
   }
  return temp.toArray ();
 }

@ The third way: Create a list set, and then through the array element into the set, and then contains () method of determining whether there has been a collection of the element to
 public static Object [] threeClear (Object [] arr) {
  List List new new = the ArrayList ();
  for (int I = 0; I <arr.length; I ++) {
   (! list.contains (ARR [I])) {IF
    List.add (ARR [I]);
   }
  }
  return List.toArray ();
 }

@ The fourth embodiment: the original two loops through the array, then one by one and judges whether the element after the repetition, also set a flag to tell whether a duplicate, a new array into the marking elements will not be repeated
 public static Object [ ] fourClear (Object [] ARR) {
 
int T = 0;

   // temporary array
  Object [] = new new xinArr Object [arr.length];
  
  for (int I = 0; I <arr.length; I ++) {
   // declaration tag, whether to repeat
   Boolean = isRepeat to true;
   for (int J = +. 1 I; J <arr.length; J ++) {
    // If there are duplicate elements is set to the flag to false
    IF (ARR [I] == ARR [J]) {
     isRepeat = to false;
     BREAK;
    }
   }
   // tag element indicates that no repeat is true
   IF (isRepeat) {
    xinArr [T] = ARR [I];
    T ++;
   }
  }
  // array duplicates removed
  Object [] = new new newArr Object [T];
  System.arraycopy (xinArr, 0, newArr, 0, T);
  return newArr;
 }

 
public static void main(String[] args) {
  Object[] arrs={1,2,5,2,45,6,23,6,3,4,3,6,5,1};
  System.out.println("one:");
  printArray(oneClear(arrs));
  System.out.println("two:");
  printArray(twoClear(arrs));
  System.out.println("three:");
  printArray(threeClear(arrs));
  System.out.println("four:");
  printArray(fourClear(arrs));
 }
public static void printArray(Object[] arr){
  for(Object object:arr){
   System.out.print(object+" ");
  }
  System.out.println("");
 }
 
result:

 

Guess you like

Origin www.cnblogs.com/jie-y/p/11134707.html