How to add a string and int and sort by the int
I am trying to program a simple console program that accepts a string and integer as input, enters them into an array, sorts them by the integer, and returns the contents开发者_JS百科 accordingly. I've been battling this program for a long time, so thanks a lot for the help :).
On approach would be to create a class that holds both the string and int parts of the info. You can create an instance for each int/string pair. Then you can put those instances in an array.
You can then sort the array using Arrays.sort. Note that your class will have to implement Comparable
as the linked API documentation says.
Instead of array, use TreeMap<Integer, String>
. TreeMap is sorted by the 'key' in the natural order. All you have to do is iterate over it.
Solution given by amit is also ok.
you should write a class with int and String as fields, and implement a Comparator for this class. insert your elements to the array, and just use Arrays.sort() to sort it.
I am going against the current here. All have advice you to use Arrays.sort() I advice you not to.
And here is the reason. When starting to learn programming I find it a funny and very good learning form to implement algorithms your self and you will have a far grater understanding of Computer Sciences if you have implemented sorting a few times your self. So do your own sorting algorithm and when you fell comfty with that then use Arrays.sort().
I wouldn't use an array for input unless you know the number of entries. You can Use ArrayList so you don't need to know.
class StringInt implement Comparable<StringInt> {
final String string;
final int num;
public StringInt(String string, int num) {
this.string = string;
this.num = num;
}
public int compareTo(StringInt si) {
return num > si.num ? +1 : num < si.num ? -1 : 0;
}
}
List<StringInt> list = new ArraysList<StringInt>();
// add element.
list.add(new StringInt("Hello", 1));
// sort them
Collections.sort(list);
精彩评论