简体   繁体   中英

Using comparable to sort array

I am writing a program where a user adds a set of Integers, and I have to use a comparable to sort the array. Here's how I'm trying to do it:

public class Set<E extends Comparable<E>> {

String s;
String name;
private static final int INITIAL_CAPACITY = 10;
private E[] theData;
private int size = 0;
private int capacity = INITIAL_CAPACITY;

@SuppressWarnings("unchecked")
public Set() {
    theData = (E[]) new Comparable[capacity];
}

public Set(String name) {
    this.name = name;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public void add(E item) {

    if (size == capacity) {
            reallocate();
        }

        if(size == 0){
            theData[0] = item;
            size++;
        }

        for (int i = 0; i < size; i++) {
            int result = item.compareTo(theData[i]);

            if (result < 0){
                theData[i+1] = theData[i];
                theData[i] = item;
                size++;
            }

            if (result > 0){
                theData[i+1] = item;

            }
        }




}

public E get(int index) {
    if (index < 0 || index >= size) {
        throw new ArrayIndexOutOfBoundsException(index);
    }
    return theData[index];
}

public int size() {
    return size;
}

private void reallocate() {
    capacity = 2 * capacity;
    theData = Arrays.copyOf(theData, capacity);
}

}

My idea with the add method is to compare each added item (the number being added to a set). If the item is less than the value of theData[i], shift theData[i] forward a spot into theData[i+1], and place the item in theData[i].

If it is greater than the value in theData[i], place the item in i+1 and leave the lower value in element i.

I've tried re-writing my loops, using a nested loop to iterate through the rest of the elements, but something must be off in my logic because I'm not getting any better results.

each time "size" in add method is initialized to "0", so your for loop is not working, no comparison is done. try using "for(int i=0; i<theData.length; i++)" instead. but after that you may face NullPointerException coz you have initialised initial capacity to 10. writing a separate compare method may work..

public int compare(E o1, E o2) {
       return o1.compareTo(o2);
}

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