Dacha
Dacha

Reputation: 3

How to find duplicates in a java array using only for, if or while?

can someone explain me how to find duplicate elements in java: array {1,5,7,4,5,1,8,4,1} using only for, if or while/do while?

Tnx in advance.

Dacha

Upvotes: 0

Views: 234

Answers (1)

marion-jeff
marion-jeff

Reputation: 799

Before you insert an element in the array, check first the content of the array. If the inserting object is equal to any then do not proceed with the insert.

Or maybe try this one:

int[] arrayObject={1,5,7,4,5,1,8,4,1};
List<Integer> uniqueList=new LinkedList<>();
List<Integer> duplicateList=new LinkedList<>();
for(int i=0; i<arrayObject.length; i++){
    if(!uniqueList.contains(arrayObject[i])){
        uniqueList.add(arrayObject[i]);
    }else if(!duplicateList.contains(arrayObject[i])){
        duplicateList.add(arrayObject[i]);
    }
}
System.out.println("Elements without duplicates: "+uniqueList);
System.out.println("Duplicated elements: "+duplicateList);

Output:
Elements without duplicates: {1, 5, 7, 4, 8}
Duplicated elements: {1, 5, 4}

Upvotes: 1

Related Questions