Reputation: 2329
I created a my own SortedSet here is the code for adding something to the array. (I know there are better and simpler ways to do this than an Array but it has to be done this way)
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; //*/
}
}
And I am testing sorted number strings like this:
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();
}
And in the output I get:
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
My question is how do I make this to be sorted the way it should be?? I know the problem is in the adding method (it should be able to sort strings and integers as well)
And it works perfectly fine when I create a SortedSet of Strings or Integers, when when I mix them like this I get this "unsorted" outcome.
Help?? Thanks.
Upvotes: 1
Views: 1644
Reputation: 3761
Those look like sorted strings to me. "1" comes before "10" just like "a" comes before "ab" in the dictionary. @MRAB has the correct suggestion to convert your strings representing numbers to actual numbers if you want them sorted in numerical order.
You can do that with a Comparator if you want to keep your set a SortedSet<String>
(error checking not performed in the snippet below):
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);
}
});
Upvotes: 2
Reputation: 20664
Convert the number strings to numbers before comparing them.
Alternatively, when comparing two number strings which are different lengths, pad the shorter one to be the same length as the longer one by adding zeros to the start.
Upvotes: 1