-3

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?

Robin Green
  • 32,079
  • 16
  • 104
  • 187

2 Answers2

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
0

Using Comparable and Comparator you can do this. This example will give you a clear idea of how to sort your list by a property of an object. In this example Student objects are sorted by their age.

example

Sandeepa
  • 3,457
  • 5
  • 25
  • 41