Given and int array; int[] arr = {1, 2, 5, 8, 9, 10, 20, 80, 9, 0, 100, 90, 30, 55, 22, 87, 88, 22, 33, 22, 1, 2, 3};
Requirement: requirement is: there is an array, which is without sorted and with duplicates. created a method which can accept int[], and after ordered and removed duplicates, return it as an int[]...
My processing solution is:
static void removingDups4(int[] arr) {
LinkedHashSet<Integer> setDups = new LinkedHashSet(Arrays.asList(arr));
for (int each : arr) {
setDups.add(each);
}
System.out.println(setDups);
int[] newArr = new int[setDups.size()];
int i = 0;
while (i < setDups.size()) {
for (int each : setDups) {
newArr[i] += each;
i++;
}
System.out.println(newArr);
}
}
output:
[[I@77459877, 0, 1, 2, 3, 5, 8, 9, 10, 20, 22, 30, 33, 55, 80, 87, 88, 90, 100] Exception in thread "main" java.lang.ClassCastException: class [I cannot be cast to class java.lang.Integer ([I and java.lang.Integer are in module java.base of loader 'bootstrap') at SearchingAnElementFromArray_BinarySearch.removingDups4(SearchingAnElementFromArray_BinarySearch.java:86) at Array.SearchingAnElementFromArray_BinarySearch.main(SearchingAnElementFromArray_BinarySearch.java:12)
Process finished with exit code 1
Instead of using a LinkedHashSet you can use a TreeSet which sorts the elements in ascending order and removes the duplicates automatically. You can then convert the TreeSet into an object array using the toArray() method and then convert it to an integer array and return it. I'm not putting the code here because it is easy to figure it out.