Pair Class – Java Implementation

Class Pair<Key, Value> – A convenience class to represent name-value pairs. pair stores a key-pair value. Two Pair objects are considered equal if key and value of one pair is matching with second key. This class also generates hash code using key and value. So hash code will also be same for two Pair objects if their keys and values are same.

Constructor Detail:

public Pair(K key,   V value)
  • Creates a new pair


  • key – The key for this pair
  • value – The value to use for this pair

Methods and description:

Return Type Method Description
key for this pair getKey() Gets the key for this pair.
value for this pair getValue() Gets the value for this pair.
int (hash code for this Pair) hashCode()
  • Generate a hash code for this Pair.
  • The hash code is calculated using both the name and the value of the Pair.
String toString() String representation of this Pair.
boolean equals(Object o)
  • If the Object to be tested is not a Pair or is null, then this method returns false.
  • Two Pairs are considered equal if and only if both the names and values are equal.


Pair<String,Integer> p1 = new Pair(1,5);
Pair p2 = new Pair(1,5);
Pair p3 = new Pair(2,6);
System.out.println(p1.equals(p2) + " " + p2.equals(p3));
Output: true false



--------toString function--------
--------equals function--------
pair1 and pair2 are equal: true
pair1 and pair3 are equal: false
pair3 and pair4 are equal: false
--------getKey and getValue function--------
key: apple and its value: 1
key: apple and its value: 1
key: banana and its value: 2
key: pineapple and its value: 4
--------hashCode function--------
Pair: apple=1 and hashCode: 1209379731
Pair: apple=1 and hashCode: 1209379731
Pair: banana=2 and hashCode: -972748765
Pair: pineapple=4 and hashCode: -1349826842
As you can see that hashcode for pair1 and pair2 are same since key and values are equal

Reference: wiki

Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.

You may also like...

%d bloggers like this: