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;
}
}