Showing posts with label Duplication in java. Show all posts
Showing posts with label Duplication in java. Show all posts

Saturday, August 18, 2012

Finding duplicate elements in given array using Set


import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;


public class DuplicateNumbersInArray {

public static void main(String args[]){
int a[]={1,2,3,4,5,6,6,4,4,3,3};

System.out.println("Duplicate elements in Array"+dupElementsUsingSet(a));
}

private static ArrayList<Integer> dupElementsUsingSet(int[] a) {
ArrayList<Integer> arr=new ArrayList<Integer>();
Set<Integer> sortset=new HashSet<Integer>();
for(int i=0;i<a.length;i++){
if(sortset.contains(a[i]))
arr.add(a[i]);
else
sortset.add(a[i]);
}
return arr;
}
}