Collections have various inbuilt methods that are very powerfull like Collections.reverse , Collections.swap , Collections.min , Collections.max etc. The condition to use these methods is the collection on which they are used the items in that collection should be comparable. Like for example an arraylist arraylists of ints ,Strings etc.
For example we have binarySearch is very fast operation . 20 comparisons can help in Search millions of items and 64 comparisons can compare a even huge number.Also note binary search method is only applicable to Lists and not Sets.
We can use various methods like Collections.binarysearch on comparable objects.
Now if we have list of objects of user define class like Seat for example then to use the above collections methods on any arraylist of objects of Seat we have to implement comparable interface on that objet class
For that Seat has to extend comparable interface and override the compareTo method
public class Seat implements Comparable<Seat> {
and then we have to override the compareTo method and then in that method we have define how do we compare various objects of this class. It will mostly be based on the various class variable present in that classs. Like in Seat class we can compare based on seatNumber where seatNumber is a class member variable and is of type String.
@Override
public int compareTo(Seat seat) {
return this.seatNumber.compareToIgnoreCase(seat.getSeatNumber());
}
}
We can then use the below code to to find an element in a list as Collections.binarySearch method is much faster and more preferred.
int foundSeat = Collections.binarySearch(seats,requestedSeat,null);
In the above method we just pass the entire list ,in our case the Arraylist named seats ,the actual element in our list we want to search for which in our case is a seat object named requestSeat and null and the binarySearch will return to us the position of the element if it is found . So if element is found then position will be >=0 or otherwise it will be negative.
And for any collection items that are comparable we can use other collection methods like Collections.min,max and sort etc
Now let us say Seat object has two variable price and seatNumber and we want to compare based on both values.So we modify our compareTo Method like below i.e sort based on two fields. first on the basis of price and then on seatNumber.
int c=Double.compare(this.price,seat.getPrice())
if(c!=0){
return c;}
return this.seatNumber.compareToIgnoreCase(seat.getSeatNumber());