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.
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.
Related
I've never messed with comparators before and I'm struggling to grasp the concept enough to implement it as a heap. Especially since I couldn't find anything online involving both comparators and heaps together. As far as my knowledge, here is the code you will need. Let me know if anything else is needed. Thanks.
//A complete tree stored in an array list representing this binary heap
private ArrayList<E> tree;
// A comparator lambda function that compares two elements of this heap when rebuilding it
private Constructor<? super E> cmp;
// constructs an empty heap using the compareTo method of its data type as the comparator
public Heap () {
}
// A parameterized constructor that uses an externally defined comparator
// #param fn - a trichotomous integer value comparator function
public Heap(Comparator<? super E> fn) {
}
Correct me if I'm wrong, but in order to use the comparator, you will need the compareTo method which is the natural comparison method. This compareTo method is of class Car and you can find information about that below. Here is the compareTo method:
public int CompareTo(Car c) {
if (year != c.year)
return year - c.year;
if(make.compareTo(c.make) != 0)
return make.compareTo(c.make);
if(make.compareTo(c.model) != 0)
return model.compareTo(c.model);
return type.compareTo(c.type);
You may or may not need this information to help me to implement these two heap constructors:
The overall goal of what I'm trying to do is to implement the main method that takes in the name of a data file and a numeric code representing the sort key (or the order the data is to be sorted using the heap). And then generate a sorted list of the data. In this specific case, I am sorting cars with the following order codes:
-2 (-make-model-type-year )
, -1 (-year-make-mode-type)
), 0 (-type+year-makemodel),
1 (+year+make+model+type) and 2 (+make+model+type+year )
The + sign indicates ascending order and the - sign indicates descending
order.
As Gene commented, you seem to be conflating Comparable and Comparator. The first notes that a class carries a compareTo method so objects of that class can sort themselves. The second indicates a class is a separate class that knows how to sort objects of a certain other class.
Generally best to use the latter (Comparator) if you want different sorting in various situations. Use the first (Comparable) when you have only a single specific sorting algorithm.
When using a Comparator, the objects being sorted need not be Comparable.
In modern Java, Comparator was enhanced with some convenient methods for building a comparator.
Comparator
.comparingInt( Car :: getYear )
.thenComparing( Car :: getMake )
.thenComparing( Car :: getModel() )
Rather than use a List, use a NavigableSet such as TreeSet to keep objects sorted.
NavigableSet< Car > cars = new TreeSet<>( myComparator ) ;
I do not understand the logic shown in the last section of your Question, so perhaps I’ve misunderstood the true nature of your query.
I got some understanding of collections which gone through some articles.
But i 'm confusing where should implement collections.sort() method and where need to use comparable interface(compareTo() and comparator interface (compare()).
Comparable interface for compare this and another reference object but comparator for compare two objects.
I would like to know exactly which situation need to use methods ?
Thanks,
You should not implement Collections.sort(); this method is built-in to Java. Call that method without supplying a Comparator to sort by the natural order, if it's Comparable. Else, supply a Comparator to sort the Comparator's way.
You should have the class implement Comparable and provide a compareTo method if the class has a natural ordering, as indicated in the Comparable javadocs. An example would be for Integer and Double, which certainly have a natural mathematical ordering.
You should create a class that implements Comparator when you cannot make the class of the object to sort Comparable or when you want to present an ordering that is an alternative to the natural ordering, or when you want to impose an order when there is no natural ordering. An example would be to reverse the natural order (say, sort descending, from largest to smallest). Another example would be a data object with multiple fields, that you want to be sortable on multiple fields, e.g. a Person object with firstName and lastName: you could have a Comparator that sorts on lastName first, and another that sorts on firstName first.
Comparator makes sense to me when I don't have access to the code of the class I whish to compare: for instance, you may need to implement a custom comparator for String.
When I need to sort lists of my own custom objects, I write them to implement interface Comparable.
Let's see if I can explain it in plain words:
The compareTo() method is design to compare the active instance of an object with another instance of an object. So, let's say you have this example class:
public class Spam implements Comparable<Spam> {
private int eggs;
public Spam(int eggs) {
this.eggs = eggs;
}
public int compareTo(Spam otherSpam) {
return otherSpam.eggs - this.eggs;
}
public int getEggs() {
return eggs;
}
}
Let's say you use this Spam class somewhere in your code:
...
if(spam1.compareTo(spam2) == 0) {
System.out.println("Both spams are equal");
} else {
if(spam1.compareTo(spam2) > 0)
System.out.println("'spam2' is bigger than 'spam1'");
else
System.out.println("'spam2' is smaller than 'spam1'");
}
....
So, compareTo() is used to decide wether two instance of a class are equal, and, if they are not equal, which one is bigger.
The importance of this for a sorting algorithm is evident now. How would you sort a collection of objects if you don't know if one is bigger than another? When an implementation of sort is called, it uses the compareTo() method of the class to decide the correct order of the collection.
Finally, the compare() method is something you use when you want to perform the comparison outside the class. An implementation of this would be:
public int compare(Spam s1, Spam s2) {
return s1.getEggs() - s2.getEggs();
}
Hope this helps you
I guess Comparator is used only when you want to sort the objects in a class in the ascending order. Used to sort say the ID's of a class in ascending order. It is mutually exclusive sorting based on one field automatically rules out sorting based on another field
There is a java bean Car that might contains two values: model and price.
Now suppose I override equals() and hashcode() checking only for model in that way:
public boolean equals(Object o) {
return this.model.equals(o.model);
}
public int hashCode() {
return model.hashCode();
}
This permit me to check if an arraylist already contain an item Car of the same model (and doesn't matter the price), in that way:
List<Car> car = new ArrayList<Car>();
car.add(new Car("carA",100f));
car.add(new Car("carB",101f));
car.add(new Car("carC",110f));
System.out.println(a.contains(new Car("carB",111f)));
It returns TRUE. That's fine, because the car already exist!
But now I decide that the ArrayList is not good, because I want to maintain the items ordered, so I substitute it with a TreeSet in this way:
Set<Car> car = new TreeSet<Car>(new Comparator<Car>() {
#Override
public int compare(Car car1, Car car2) {
int compPrice = - Float.compare(car1.getPrice(), car2.getPrice());
if (compPrice > 0 || compPrice < 0)
return compPrice;
else
return car1.getModel().compareTo(car2.getModel());
}});
car.add(new Car("carA",100f));
car.add(new Car("carB",101f));
car.add(new Car("carC",110f));
System.out.println(a.contains(new Car("carB",111f)));
But now there is a problem, it return FALSE... why?
It seems that when I invoke contains() using an arrayList the method equals() is invoked.
But it seems that when I invoke contains() using a TreeSet with a comparator, the comparator is used instead.
Why does that happen?
TreeSet forms a binary tree keeping elements according to natural (or not) orders, so in order to search quickly one specific element is the collection, TreeSet uses Comparable or Comparator instead of equals().
As TreeSet JavaDoc precises:
Note that the ordering maintained by a set (whether or not an explicit
comparator is provided) must be consistent with equals if it is to
correctly implement the Set interface. (See Comparable or Comparator
for a precise definition of consistent with equals.) This is so
because the Set interface is defined in terms of the equals operation,
but a TreeSet instance performs all element comparisons using its
compareTo (or compare) method, so two elements that are deemed equal
by this method are, from the standpoint of the set, equal. The
behavior of a set is well-defined even if its ordering is inconsistent
with equals; it just fails to obey the general contract of the Set
interface.
We can find a similarity with the HashCode/Equals contract:
If equals() returns true, hashcode() has to return true too in order to be found during search.
Likewise with TreeSet:
If contains() (using Comparator or Comparable) returns true, equals() has to return true too in order to be consistent with equals().
THEREFORE: Fields used within TreeSet.equals() method have to be exactly the same (no more, no less) than within your Comparator implementation.
A TreeSet is implicitly sorted, and it uses a Comparator for this sorting. The equals() method can only tell you if two objects are the same or different, not how they should be ordered for sorting. Only a Comparator can do that.
More to the point, a TreeSet also uses comparisons for searching. This is sort of the whole point of tree-based map/set. When the contains() method is called, a binary search is performed and the target is either found or not found, based on how the comparator is defined. The comparator defines not only logical order but also logical identity. If you are relying on logical identity defined by an inconsistent equals() implementation, then confusion will probably ensue.
The reason for the different behaviour is, that you consider the price member in the compare method, but ignore it in equals.
new Car("carB",101f) // what you add to the list
new Car("carB",111f) // what you are looking for
Both instances are "equals" (sorry...) since their model members are equal (and the implementation stops after that test). They "compare" as different, though, because that implementation also checks the price member.
I've been browsing a lot of similar questions in here and on other sites. Still I can't seem to get my head wrapped around this problem.
I have a class:
public class Event {
public String Item;
public String Title;
public String Desc;
#Override
public boolean equals(Object o) {
return true;
}
}
I'm trying to use this class in an ArrayList<Event> events but I can't find a way to get events.contains("item") to work. I have tried debuging and I've found that it doesn't even enter the overridden method.
What am I doing wrong?
That's because you're breaking symmetry as specified in the contract of equals(): if any event equals to "item" (which is a String), "item" should also be equal to any event.
Actually, what Java does is to call indexOf("item") on your list, and check if it is positive.
Now, indexOf() works like this in an ArrayList for instance (see complete source code here):
for (int i = 0; i < size; i++)
if ("item".equals(elementData[i]))
return i;
So basically it is the String's equals() method which is called here, not your one which is returning false of course.
Solve this issue by simply specifying an Event parameter to the function, like:
events.contains( new Event("item", "title", "desc") )
Note that you'll have to create a proper constructor for your class ot initialize the members.
You should also override public int hashCode(). The two methods are closely related.
Read more about this: http://www.javapractices.com/topic/TopicAction.do?Id=17
When you override equals() method, you also have to override the hashcode() method because they go hand in hand. If two object are equal, then they have to have the same hashcode. Hashmaps use this to evaluate the save locations. If two objects are not equal, they may or may not have the same hashcode.
In this case, you need only override equals method, not the hashCode method.
The hashCode and equals method should both be overrided when you want to use the object of your class as key in HashMap. HashMap uses a structure of array + linkedList. When adding a key-value pair, it first do some calculation based on key's hashCode to get the index in array; then go throught the linkedList at that index position to find if the key-value pair is already there. If yes, it will overwrite the record with new value; otherwise add the key-value pair to the end of that linkedList. When locating a key, the process is smiliar. So if the hashCode method is not overrided, you will fail the first round search in the array. That's the reason why you need override both methods. It's not like somewhere says there's contract between these two methods or they have close relation.
Say I have a Song object like
public Song(){
String artist, title;
StringBuilder lyrics;
int rank;
}
Is it possible to have multiple compare methods that, depending on the collection used, sort by a particular field? This object already has a compare method for ordering based on the artist and title values, and I would like to be able to order based on the rank.
My current project requires us to run a search on the lyrics of the Song and return a high to low match list. I want to use a PriorityQueue to hold the matches based on rank value.
Normally I would simply create another object to hold the Song and the rank, but this project not only plugs into a GUI interface provided by the professor, which requires any results be passed in an Song[] array, but prints out the first ten values as Rank, Artist, Title.
I can use toArray() to convert the queue, but if I use it to store anything other than Song objects, it will throw an ArrayStoreException.
So is this possible, or do I have to modify the existing compare method to sort by integer value?
Use a Comparator.
Comparator<Song> rankOrder = new Comparator<Song>() {
public int compare(Song s1, Song e2) {
return s1.rank - s2.rank;
}
};
Collections.sort(songs, rankOrder);
See http://download.oracle.com/javase/tutorial/collections/interfaces/order.html
Most ordered collections have a constructor that takes a Comparator as an argument. Define a few static comparators in your Song class and then define things as follows:
Set<Song> allSongs = new TreeSet<Song>(Song.BY_TITLE);
PriorityQueue<Song> rankedSongs = new PriorityQueue<Song>(10, Song.BY_RANK);
There are utility classes (e.g., Guava Ordering) that can help you build up other comparators from the basics.
The compareTo method of the Comparable interface typically offers the default comparison, if you want to provide another you should write a Comparator object.
You could use the constructor PriorityQueue(int, Comparator<? super E>) to use a different ordering.
Is there a reason for using a PriorityQueue apart from sorting?
PriorityQueue is not only inefficient if you do not need to have it sorted after each new element but can also not be used to sort in different ways. You would need a different PriorityQueue for each desired sorting.
Using a List could be sufficient and would allow you to sort using a different Comparator whenever you like: Collections.sort(List<T> list, Comparator<? super T>)
Instead of implementing Comparable in Song, pass a custom Comparator to your Collection of choice.
See Object Ordering for further details.