简体   繁体   中英

Removing a redundant value in an array

I am not sure why my removeDuplicates method refuses to actually get rid of non-unique values. I am not sure if the problem is with the size incrementation or my method call.

// 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 - 1);
        }
    }
}

@user98643 -

Jano's suggestion is spot-on correct: the best solution is to simply use the appropriate data structure, for example a TreeSet .

SUGGESTIONS:

1) In general, always consider using a container such a "List<>" in preference to an array

2) In general, look for the container that already has most of the properties you need

3) In this case, A) you want all elements sorted, and B) each element must be unique.

A TreeSet fits the bill beautifully.

IMHO..

http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html

http://math.hws.edu/javanotes/c10/s2.html

http://www.mkyong.com/java/what-is-the-different-between-set-and-list/

Try this..

// Convert it to list as we need the list object to create a // set object. A set is a collection object that cannot have // a duplicate values, so by converting the array to a set // the duplicate value will be removed.

List<String> list = Arrays.asList(data);
Set<String> set = new HashSet<String>(list);

System.out.print("Remove duplicate result: ");

//
// Create an array to convert the Set back to array.
// The Set.toArray() method copy the value in the set to the
// defined array.
//
String[] result = new String[set.size()];
set.toArray(result);
for (String s : result) {
    System.out.print(s + ", ");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM