在Java中将排序后的数字字符串添加到SortedSet时出现问题

问题描述

|| 我创建了自己的SortedSet,这里是向数组添加内容代码。 (我知道有比数组更好,更简单的方法,但是必须以这种方式完成)
public boolean add(AnyType x){
    if(this.contains(x))
        return false;
    else if(this.isEmpty()){
        items[theSize]=x;
        theSize++;
        return true;
    }
    else{
    if( theSize == items.length )
        this.grow();
    //Here goes code for adding
    theSize++;
    AnyType[] newItems = (AnyType[]) new Comparable[theSize];
    for(int i=0;i<theSize-1;i++)
        if(items[i].compareto(x)>0){
            newItems[i]=x;
            newItems[i+1]=items[i];
            for(int j=i+2;j<theSize;j++)
                newItems[j]=items[j-1];
            items = newItems;
            return true;
        }
        else
            newItems[i]=items[i];
    newItems[theSize-1] =x;
    items=newItems;
    return true; //*/
    }
}
我正在测试像这样的排序数字字符串:
public static void main(String[] a) {


    SortedSet<String> s1 = new SortedSet<String>();
    final int NUM1 = 37;
    final int NUM2 = 53;
    final int NUM3 = 61;

    for (int i = NUM1; i != 0; i = (i + NUM1) % NUM3) {
        s1.add(\"\" + i);
    }
    s1.show();
    for (int i = NUM1; i != 0; i = (i + NUM1) % NUM3) {
        s1.add(\"\" + i);
    }
    s1.show();
    for (int i = NUM1; i != 0; i = (i + NUM1) % NUM2) {
        s1.remove(\"\" + i);
    }

    s1.show();

    }
输出中,我得到:   1 10 11 12 13 14 15 16 17 18 19 2 20 21 22 23 24 25 26 27 28 29 3 30 31 32 33 34 35 36 37 38 39 4 40 41 42 43 44 45 46 47 48 49 5 50 51 52 53 54 55 56 57 58 59 6 60 7 8 9 我的问题是如何使它按应有的方式排序?我知道问题出在添加方法中(它也应该能够对字符串和整数进行排序) 当我创建字符串或整数的SortedSet时,它工作得很好,当我像这样混合它们时,得到的结果是“未排序”。 救命?? 谢谢。     

解决方法

        在我看来,那些看起来像是分类的琴弦。 \“ 1 \”在\“ 10 \”之前,就像字典中\“ a \”在\“ ab \”之前一样。如果您希望将代表数字的字符串转换为实际数字,@ MRAB有正确的建议。 如果您想将设置保持为
SortedSet<String>
,可以使用比较器进行此操作(以下代码段未执行错误检查):
    SortedSet<String> s1 = new TreeSet<String>(new Comparator<String>() {
        /**
         * Returns a positive value if number1 is larger than number 2,a
         * negative number if number1 is less than number2,and 0 if they
         * are equal.
         */
        public int compare(String number1,String number2) {
            return Integer.parseInt(number1) - Integer.parseInt(number2);
        }
    });
    ,        在比较之前将数字字符串转换为数字。 或者,当比较两个不同长度的数字字符串时,通过在开头加上零来填充较短的数字,使其与较长的数字相同。