JAVAME:排序Java Vector

时间:2010-12-20 14:55:06

标签: java java-me vector

在JAVAME中对Java Vector进行排序的最佳和最有效的方法是什么。

我的对象有五个属性,我想按名为price的{​​{1}}属性进行排序。在我的Vector中,我最多可以有150个项目。我们将非常感谢示例代码。

Thanx你的时间。

3 个答案:

答案 0 :(得分:2)

使用Collections.sort(List< T> vector,Comparator< T> c)方法。如果Java ME中没有这样的方法,只需从Java SE复制它。它使用合并排序算法,因此复制起来并不多。

答案 1 :(得分:-1)

import java.lang.reflect.Field;
import java.util.*;

public class Sorter {

    public static List sort(List list, String fieldName, boolean asc) {
        Comparator c = new FieldComparator(fieldName, asc);
        Collections.sort(list, c);
        return list;
    }

    public static int compareNumbers(Number n1, Number n2) {
        double d1 = n1.doubleValue();
        double d2 = n2.doubleValue();

        if (d1 < d2) {
            return -1;
        }
        if (d2 < d1) {
            return 1;
        }
        return 0;
    }

    public static int compareDates(Date d1, Date d2) {
        long l1 = d1.getTime();
        long l2 = d2.getTime();

        if (l1 < l2) {
            return -1;
        }
        if (l2 < l1) {
            return 1;
        }
        return 0;
    }

    public static int compareStrings(String s1, String s2) {
        return s1.compareTo(s2);
    }

    public static Object getFieldValue(Object obj, String fn) {
        try {
            Class clazz = obj.getClass();
            Field f = null;
            try {
                f = clazz.getDeclaredField(fn);
            } catch (Exception e) {}

            while (f == null && clazz.getSuperclass() != null) {
                clazz = clazz.getSuperclass();
                try {
                    f = clazz.getDeclaredField(fn);
                } catch (Exception e) {}
            }//while

            if (f != null) {
                f.setAccessible(true);
                return f.get(obj);
            }
        } catch (IllegalAccessException e) {}
        return null;
    }

    protected static class FieldComparator implements Comparator {
        String fieldName;
        int asc;

        protected FieldComparator(String fieldName, boolean asc) {
            this.fieldName = fieldName;
            this.asc = asc ? 1 : -1;
        }

        public int compare(Object o1, Object o2) {
            if (o1 == null) {
                if (o2 == null) {
                    return 0;
                } else {
                    return -1 * asc;
                }
            }

            if (o2 == null) {
                return asc;
            }

            //compare fields
            Object fieldValue1 = getFieldValue(o1, fieldName);
            Object fieldValue2 = getFieldValue(o2, fieldName);

            if (fieldValue1 == null) {
                if (fieldValue2 == null) {
                    return 0;
                } else {
                    return -1 * asc;
                }
            }

            if (fieldValue2 == null) {
                return asc;
            }

            //both field values aren't nulls
            if (fieldValue1 instanceof Number && fieldValue2 instanceof Number) {
                return compareNumbers((Number) fieldValue1, (Number) fieldValue2) * asc;
            } else if (fieldValue1 instanceof Date && fieldValue2 instanceof Date) {
                return compareDates((Date) fieldValue1, (Date) fieldValue2) * asc;
            } else {
                return compareStrings(fieldValue1.toString(), fieldValue2.toString()) * asc;
            }
        }
    }

    public static void main(String[] args) {
        ArrayList source = new ArrayList();
        source.add(new TestNumber(5));
        source.add(new TestNumber(1));
        source.add(new TestNumber(4));
        source.add(new TestNumber(2));
        source.add(new TestNumber(3));

        List dest = sort(source, "value", true);
        out(dest);

        source = new ArrayList();
        source.add(new TestString("cc"));
        source.add(new TestString("dd"));
        source.add(new TestString("bb"));
        source.add(new TestString("ee"));
        source.add(new TestString("aa"));

        dest = sort(source, "value", false);
        out(dest);
    }

    private static class TestNumber {
        private int value;

        public TestNumber(int v) {
            value = v;
        }

        public String toString() {
            return "" + value;
        }
    }

    private static class TestString {
        private String value;

        public TestString(String v) {
            value = v;
        }

        public String toString() {
            return "" + value;
        }
    }

    private static void out(List list) {
        for (Object obj : list) {
            System.out.println("" + obj.toString());
        }
        System.out.println("----------------------------");
    }
}

答案 2 :(得分:-1)

来自JavaSE的调整后代码:

public static void sort(List<YourObject> list) {
    Object[] a = list.toArray();
    sort(a);
    ListIterator<YourObject> i = list.listIterator();
    for (int j=0; j<a.length; j++) {
        i.next();
        i.set((YourObject)a[j]);
    }
}

public static void sort(YourObject[] a) {
    YourObject[] aux = (YourObject[])a.clone();
    mergeSort(aux, a, 0, a.length, 0);
}

private static void mergeSort(YourObject[] src,
              YourObject[] dest,
              int low,
              int high,
              int off) {
int length = high - low;

// Insertion sort on smallest arrays
    if (length < INSERTIONSORT_THRESHOLD) {
        for (int i=low; i<high; i++)
            for (int j=i; j>low &&
         dest[j-1].getPrice()-dest[j].getPrice()>0; j--)
                swap(dest, j, j-1);
        return;
    }

    // Recursively sort halves of dest into src
    int destLow  = low;
    int destHigh = high;
    low  += off;
    high += off;
    int mid = (low + high) >>> 1;
    mergeSort(dest, src, low, mid, -off);
    mergeSort(dest, src, mid, high, -off);

    // If list is already sorted, just copy from src to dest.  This is an
    // optimization that results in faster sorts for nearly ordered lists.
    if (src[mid-1].getPrice()-src[mid].getPrice() <= 0) {
        System.arraycopy(src, low, dest, destLow, length);
        return;
    }

    // Merge sorted halves (now in src) into dest
    for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
        if (q >= high || p < mid && src[p].getPrice()-src[q].getPrice()<=0)
            dest[i] = src[p++];
        else
            dest[i] = src[q++];
    }
}