gpt4 book ai didi

java - 将排序后的数字字符串添加到 Java 中的 SortedSet 的问题

转载 作者:行者123 更新时间:2023-11-29 06:12:53 24 4
gpt4 key购买 nike

我创建了一个我自己的 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);
}
});

关于java - 将排序后的数字字符串添加到 Java 中的 SortedSet 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6194970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com