Wednesday 19 August 2015

Java program to check if Array contains duplicate elements or not



                         Java program to check if Array contains duplicate elements or not


Arrays are important concept in Java.Everyone should be comfortable with arrays as they are quite often used in programming.

To check if declared array contains unique element or it has duplicates ,below is the sample program

 /**  
  * @author Dixit  
  *   
  */  
 public class DuplicateElement {  
      public static void main(String a[]) {  
           int arr[] = { 1, 2, 3, 4, 1 };  
           System.out.println("Result:-" + hasNoDuplicates(arr));  
           int newArr[] = { 1, 2, 3, 4 };  
           System.out.println("Result:-" + hasNoDuplicates(newArr));  
      }  
      public static boolean hasNoDuplicates(final int[] intArray) {  
           for (int i = 0; i < intArray.length; i++) {  
                if (!isIntUniqueInArray(intArray[i], intArray))  
                     return false;  
           }  
           return true;  
      }  
      private static boolean isIntUniqueInArray(final int value,  
                final int[] intArray) {  
           int occurs = 0;  
           for (int i = 0; i < intArray.length && occurs < 2; i++) {  
                if (intArray[i] == value) {  
                     occurs++;  
                }  
           }  
           return occurs == 1;  
      }  
 }  


Enjoy Programming :)

No comments:

Post a Comment