Reputation: 3
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
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