Writing a public int method compareTo () java

I have an appointment where I need to create an arraylist of BookInventory objects with parameters (String bookNum, String bookTitle, int qoh, double bookPrice). Where bookNum is the debut number of the ISBN of the book. After creating this array, I need to use the Collections class sort method. In my BookInventory class, I have to write compareTo (), which will finish sorting arraylist bookNum (which is String). How can I do it? This is my first experience with this, and I do not understand.

+7
source share
3 answers

This should help you:

public class BookInventory implements Comparable<BookInventory> { // code public int compareTo(BookInventory other){ return bookTitle.compareTo(other.bookTitle); } //code } 

Distracting from this is to implement Comparable so that you can implement your own compareTo method, which is automatically called when ArrayList is sorted.

To learn more about compareTo and ordering, check out this:

http://download.oracle.com/javase/tutorial/collections/interfaces/order.html

+16
source

If you look at the documentation for the Collections class , you will see that it implements two sort mwethods. For any List element, a Comparator object is used to compare list elements. The other accepts a List any object that implements Comparable . Since compareTo determined by Comparable (while Comparator should implement compare ), this tells you that your class should be declared as implements Comparable<BookInventory> , which means that it must have a compareTo method. See the documentation for Comparable.compareTo(T) for what your method should do. You will find the String compareTo(String) method useful.

+1
source

The compareTo () method is used to compare two objects that have several properties. It will return an integer to indicate which of the compared objects is larger. It makes sense if the objects that are being compared have properties that have a natural order.

Return value:

  • less than 0 → indicates that the object is in front of the transferred object.
  • greater than 0 → the object after the transferred object
  • equal to 0 →, both objects are on the same level
+1
source

All Articles