![]() |
VOOZH | about |
The Vector class in java implements a dynamic array i.e. it can grow and shrink according to the elements that we insert or remove to/from it. It implements the List interface so it supports all the methods provided by the List interface.
In this article, we are going to discuss how we can find the minimum and maximum elements of a Vector using the Comparable interface in Java.
We can use the Collections.min() and Collections.max() methods to find the minimum and maximum elements inside our Vector. But when we are using our custom class and we want to use Collections.min() and Collections.max() method then we first need to override the compareTo() method of the Comparable interface so that java is able to compare the instances of our custom class. Also since we want to compare the object, not the primitive data types, we have to use the custom-defined compareTo() method of the Comparable interface.
Syntax to implement Comparable<T> interface:
class Account implements Comparable<Account>
Using the above syntax we can implement the Comparable interface for our custom class, i.e. Account class.
Syntax to override CompareTo() method:
@Override
public int compareTo(Account o) {
// this refers to the current object(child object)
// and o is the parent object.
return this.balance - o.balance;
}The above compareTo() compares the Account objects on the basis of their balance attribute. Our compareTo() method must return:
Below is the Code Implementation to find a minimum and maximum element of the vector using the comparable interface.
Nandini has the minimum balance of Rs 50 Pooja has the maximum balance of Rs 50000