I have an assignment where I need to create an arraylist of BookInventory objects with params (String bookNum, String bookTitle, int qoh, double bookPrice). Where bookNum is the hyphenated ISBN number of a book. After creating this array, I need to use the sort method of the Collections class. In my entity BookInventory class, I need to write a compareTo() that will end up sorting the arraylist by bookNum (which is a String). How do I do this? This is my first experience with this, and I don't understand.
Java Integer compareTo() methodThis method compares two integer objects numerically. It returns the result of the value 0 if Integer is equal to the argument Integer, a value less than 0 if Integer is less than the argument Integer and a value greater than 0 if Integer is greater than the argument Integer.
Integer. compareTo() compares two Integer objects numerically. If x>y then the method returns an int value greater than zero.
The compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The method returns 0 if the string is equal to the other string.
This should get you started:
public class BookInventory implements Comparable<BookInventory> {
// code
public int compareTo(BookInventory other){
return bookTitle.compareTo(other.bookTitle);
}
//code
}
The thing to take away from this is to implement Comparable so that you can implement your own custom compareTo method thats automatically called when you sort an ArrayList.
To read more about compareTo and ordering, check out this:
http://download.oracle.com/javase/tutorial/collections/interfaces/order.html
The compareTo() method is used to compare two objects which have multiple properties. It will return an integer to indicate which of the objects that was compared is larger. It makes more sense if the objects being compared have properties which have a natural order.
Return value:
If you look a the documentation for the Collections class, you will see that it implements two sort
mwethods. One takes any kind of List
together with a Comparator
object for comparing elements of the list. The other takes a List
of any kind of object that implements Comparable
. Since compareTo
is defined by Comparable
(while a Comparator
must implement compare
), that tells you that your class must 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 must do. You will find the String
method compareTo(String)
to be useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With