I have been given a task to write my own implementation for removing duplicate objects from an array. The array is unsorted.
As an example, I have this array of objects
ItemsList[] objects = {
new ItemsList("ob1"),
new ItemsList("ob2"),
new ItemsList("ob2"),
new ItemsList("ob1"),
new ItemsList("ob3")
};
"ob1" stands for itemId
My goal is to get the result array like this ["ob1", "ob2", "ob3"]
, but given NullPointerException when trying to find objects that aren't doubled and add those to array.
Note: cannot use Set, HashSet, ArrayList, Arrays.copyOf, Sort etc. or any other tools such as iterators.
So far I've done this:
public String[] removeDuplicates(ItemsList[] objects) {
String[] noDubs = new String[objects.length];
int len = objects.length;
int pos = 0;
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (objects[i].getItemId().equals(objects[j].getItemId())) {
noDubs[pos] = objects[i].getItemId();
pos++;
}
else {
//NullPointerException given
if (!objects[i].getItemId().equals(objects[j].getItemId()) && !objects[i].getItemId().contains(noDubs[i])) {
noDubs[pos] = objects[i].getItemId();
pos++;
}
}
}
}
String[] result = new String[pos];
for(int k = 0; k < pos; k++) {
result[k] = noDubs[k];
}
return result;
}
getItemId
is class ItemsList method