Be the first user to complete this post

  • 0
Add to List
Beginner

265. Java Pair Class

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

Parameters:

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

Methods and description:

Return TypeMethodDescription
key for this pairgetKey()Gets the key for this pair.
value for this pairgetValue()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.
StringtoString()String representation of this Pair.
booleanequals(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.

Example:

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

Output:

--------toString function--------
apple=1
apple=1
banana=2
pineapple=4
--------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