OneBite.Dev - Coding blog in a bite size

remove duplicates from an array in java

Code snippet on how to remove duplicates from an array in java

  public static int[] removeDuplicates(int[] arr){  
        int n = arr.length;  
        for (int i = 0; i < n; i++)  {  
            for (int j = i+1; j < n; j++) {  
                if(arr[i] == arr[j]){  
                    arr[j] = arr[n-1];  
                    n--;  
                    j--;  
                }  
            }  
        } 
        int[] newarr = Arrays.copyOf(arr, n);  
        return newarr;  
    }  

This code compares each number in the array with all of the other numbers. Whenever it finds a duplicate, it removes that number by setting the duplicate value equal to the last element in the array, and decrements the length of the array. Finally, it creates a new array of the new, reduced length. Each number in the new array is unique.

java