开发者

writing a public int compareTo() method java

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 sort开发者_运维问答ing 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.


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:

  • less than 0 -> indicates that the object is before the passed in object.
  • more than 0 -> the object is after the passed object
  • equal to 0 -> the two objects are at same level


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜