Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.help > #2801
| Newsgroups | comp.lang.java.help |
|---|---|
| Date | 2013-10-12 22:18 -0700 |
| Message-ID | <ca6512ad-67f1-43e1-8aea-a8a7b5641872@googlegroups.com> (permalink) |
| Subject | How to remove duplicate values in an array. |
| From | miss.smileyfish@gmail.com |
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--;
}
Back to comp.lang.java.help | Previous | Next — Next in thread | Find similar
How to remove duplicate values in an array. miss.smileyfish@gmail.com - 2013-10-12 22:18 -0700
Re: How to remove duplicate values in an array. Steven Simpson <ss@domain.invalid> - 2013-10-13 10:00 +0100
Re: How to remove duplicate values in an array. Joerg Meier <joergmmeier@arcor.de> - 2013-10-13 12:09 +0200
Re: How to remove duplicate values in an array. Roedy Green <see_website@mindprod.com.invalid> - 2013-10-21 20:34 -0700
Re: How to remove duplicate values in an array. Lew <lewbloch@gmail.com> - 2013-10-23 15:58 -0700
csiph-web