So I've made an ArrayList of Catalogue Entries, where CatalogueEntry is made up of an int, a string and a status (which has been previously defined). I want to order the elements of the list (aka the Catalogue Entries) according to their integer. Is there any way I can do this?
Asked
Active
Viewed 42 times
-3
-
2Where is your code? What error you are getting? – Amit Bera Nov 24 '18 at 14:33
-
1There almost certainly is. But this isn't how SO works; please check the FAQ. – Dave Newton Nov 24 '18 at 14:39
-
Can be done using Camparable or Comparator explained [`here`](https://stackoverflow.com/a/2784576/4594429) – saurav omar Nov 24 '18 at 14:50
2 Answers
1
Yes there is, but you must tell the program what do you mean by saying that one CatalogueEntry is bigger then an other. There are multiple ways of doing this but one example is the Comparable interface
public class CatalogueEntry implements Comaparable<CatalogueEntry> {
private int yourInt;
//methods, variables here
@Override
public int compareTo(CatalogueEntry other){
if(this.yourInt == other.yourInt) return 0;
if(this.yourInt > other.yourInt) return 1;
return -1;
}
As you can see you must implement the compareTo method and return 0 if the other entry is equal to this, -1 is its bigger and 1 if it's smaller! This way the program will know how to sort these objects and you can just use the ArrayList's sort method!

Gtomika
- 845
- 7
- 24