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:
- Zero: when both Objects are equal.
- Negative value: when the current object is less than the passed object i.e. ‘o’.
- Positive value: when the current object is greater than the passed object.
Below is the Code Implementation to find a minimum and maximum element of the vector using the comparable interface.
Java
import java.util.Collections;
import java.util.Vector;
class Account implements Comparable<Account> {
private String name;
private int balance;
public Account(String name, int balance)
{
this .name = name;
this .balance = balance;
}
public String getName() { return name; }
public int getBalance() { return balance; }
@Override public int compareTo(Account o)
{
return this .balance - o.balance;
}
}
public class GFG {
public static void main(String[] args)
{
Vector<Account> accountVector = new Vector<>();
accountVector.add( new Account( "Rahul" , 10000 ));
accountVector.add( new Account( "Anjali" , 2000 ));
accountVector.add( new Account( "Rohan" , 5000 ));
accountVector.add( new Account( "Pooja" , 50000 ));
accountVector.add( new Account( "Nandini" , 50 ));
Account minAccount = Collections.min(accountVector);
Account maxAccount = Collections.max(accountVector);
System.out.println(
minAccount.getName()
+ " has the minimum balance of Rs "
+ minAccount.getBalance());
System.out.println(
maxAccount.getName()
+ " has the maximum balance of Rs "
+ maxAccount.getBalance());
}
}
|
OutputNandini has the minimum balance of Rs 50
Pooja has the maximum balance of Rs 50000