public int userCompare(String s1, int i1, String s2, int i2){
String[] alphabety = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
String[] firstThing = s1.split("(?!^)");
String[] secondThing = s2.split("(?!^)");
}
How do I complete the following:
Create a method called userCompare that will return a -1, 1, or 0 based on the following: We have data for two users, A and B, each with a String name and an int id. The goal is to order the users such as for sorting. Return -1 if A comes before B, 1 if A comes after B, and 0 if they are the same. Order first by the string names, and then by the id numbers if the names are the same.
2
Answers
I’d compare each component individually, and then use
signum
to get strictly1
,-1
or0
.Side note – for the purpose of sorting in Java, you don’t need to strictly return
1
,-1
or0
, you can just return an arbitrary positive, negative or zero value. In other words, the usage ofsignum
is required by question, but isn’t strictly required for sorting.I would utilize the String#compareTo, and Integer#compare methods here.
If you’re looking to implement the actual comparison routine, review the source for each of those methods.
For a String, it’s just a traversal of the bytes.
Here is utilized StringLatin1#compareTo method.
GitHub – OpenJDK – StringLatin1.java – compareTo(byte[], byte[], int, int).
And, for an Integer it’s just a relational, and equality, operation.
GitHub – OpenJDK – Integer.java – compare(int, int).