Reputation: 3
I have this following code snippet and want to print unique elements of the array a[]
I want to print the result in main method by returning an array.
Following code returning a result- 10 20 21 34 0 56 65 0 76 67 45 55 0 99 23 0 0 0 12
Can anyone please tell me where I am doing the mistake?
public class uniqueElements {
static int[] newArr=null;
public static void main(String[] args){
int[] a=new int[] {10,20,21,34,21,56,65,65,76,67,45,55,10,99,23,67,99,34,12};
int[] b=uniqueElements(a);
for(int i:b){
System.out.print(i+" ");
}
}
private static int[] uniqueElements(int[] arr) {
newArr=new int[arr.length];
for(int i=0;i<arr.length;i++){
boolean isDistinct = false;
for(int j=0;j<i;j++){
if(arr[i] == arr[j]){
isDistinct = true;
break;
}
}
if(!isDistinct){
newArr[i]=arr[i];
}
}
return newArr;
}
}
Upvotes: 0
Views: 732
Reputation: 309
The easiest way to remove repeated elements is to add the contents to a Set (which will not allow duplicates) and then add the Set back to the ArrayList
public class uniqueElements {
static int[] newArr=null;
public static void main(String[] args){
int[] a=new int[] {10,20,21,34,21,56,65,65,76,67,45,55,10,99,23,67,99,34,12};
int[] b=uniqueElements(a);
for(int i:b){
System.out.print(i+" ");
}
}
private static int[] uniqueElements(int[] a) {
// add elements to a, including duplicates
HashSet hs = new HashSet();
hs.addAll(a);
a.clear();
a.addAll(hs);
return a;
}
}
Upvotes: 1
Reputation: 393771
You copy distinct values from the input array to the same index in the output array, which means the indices of duplicate values will remain 0, which is what you see in your output.
A possible solution :
private static int[] uniqueElements(int[] arr)
{
newArr=new int[arr.length];
int count = 0;
for(int i=0;i<arr.length;i++){
boolean isDistinct = false;
for(int j=0;j<i;j++){
if(arr[i] == arr[j]){
isDistinct = true;
break;
}
}
if(!isDistinct) {
newArr[count]=arr[i];
count++;
}
}
return newArr;
}
This would return an array whose first count
elements are the unique values of the input array. It would still have some 0s at the end. To eliminate these 0s, you can create a new array of count
elements and copy the first count
elements of newArr
to it.
BTW, your isDistinct
flag has the exact opposite meaning to what its name implies. You set it to true when you find a duplicate.
Upvotes: 1
Reputation: 193
You can also use a Set if you only want unique values:
http://docs.oracle.com/javase/7/docs/api/java/util/Set.html
Set<Integer> b = new HashSet<Integer>(Arrays.asList(a));
But if you still want to do it manually, you can do as the other people said.
Upvotes: 2