m***@gmail.com
2013-10-13 05:18:15 UTC
I have some code to build an object elementData that stores a list of ints in an array and also keeps track of a boolean unique that determines if duplicates are allowed in a list. I have written a small method to search out duplicates and remove them, but for some reason it is not working. I am not sure if the problem is with the method itself or the placement of the call to the removeDuplicates method.
// post: places the value in the correct place based on ascending order
public void add(int value) {
size++;
if (size == 1) {
elementData[0] = value;
} else {
int position = Arrays.binarySearch(elementData, 0, size - 1, value);
if (position < 0 ) {
position = (-position) - 1;
}
for (int i = size - 1; i > position; i--) {
elementData[i] = elementData[i - 1];
}
elementData[position] = value;
if (unique) {
removeDuplicates();
}
}
}
//post: removes any duplicate values from the list
private void removeDuplicates() {
for(int i = size - 1; i < 0; i--) {
if (elementData[i] == elementData[i - 1]){
remove(i);
}
}
}
// pre : 0 <= index < size() (throws IndexOutOfBoundsException if not)
// post: removes value at the given index, shifting subsequent values left
public void remove(int index) {
checkIndex(index);
for (int i = index; i < size - 1; i++) {
elementData[i] = elementData[i + 1];
}
size--;
}
// post: places the value in the correct place based on ascending order
public void add(int value) {
size++;
if (size == 1) {
elementData[0] = value;
} else {
int position = Arrays.binarySearch(elementData, 0, size - 1, value);
if (position < 0 ) {
position = (-position) - 1;
}
for (int i = size - 1; i > position; i--) {
elementData[i] = elementData[i - 1];
}
elementData[position] = value;
if (unique) {
removeDuplicates();
}
}
}
//post: removes any duplicate values from the list
private void removeDuplicates() {
for(int i = size - 1; i < 0; i--) {
if (elementData[i] == elementData[i - 1]){
remove(i);
}
}
}
// pre : 0 <= index < size() (throws IndexOutOfBoundsException if not)
// post: removes value at the given index, shifting subsequent values left
public void remove(int index) {
checkIndex(index);
for (int i = index; i < size - 1; i++) {
elementData[i] = elementData[i + 1];
}
size--;
}