Mani
Mani

Reputation: 2649

Difference between Pair and Hashmap?

What is the necessity to introduce Pair class when Hashmap can do the same job?

I see Pair being introduced to Java version 8

Upvotes: 15

Views: 26610

Answers (4)

Basil Bourque
Basil Bourque

Reputation: 338624

Map.Entry

Actually, the Map.Entry interface and its two concrete implementations:

… are more akin to a Pair class than is HashMap.

In olden days those two implementing classes were indeed used by some folks to represent a “pair” without any Map.

final int x = 7 , y = 42 ;
Map.Entry < Integer , Integer > point = new AbstractMap.SimpleImmutableEntry<> ( x , y ) ;

See this code run at Ideone.com.

point.toString() ➡️ 7=42

Records

The need for that use (abuse?) of those classes evaporated with the arrival of Java records. Now we can easily define our own pairing class such as Point with no fuss and no muss.

record Point ( int x , int y ) {}

Usage:

Point p = new Point( 7 , 42 ) ;

p.toString() ➡️ Point[x=7, y=42]

JavaFX

As others noted, names matter, especially in Java norms. The naming of the class Pair is more self-documenting than something like AbstractMap.SimpleImmutableEntry. That Pair class is specific to JavaFX, and using that name makes good sense in that context.

Upvotes: 0

db07
db07

Reputation: 117

A pair is basically a convenient way of associating a simple key to a value. Maps do the same thing to store key-value pairs but maps stores a collection of pairs and operate them as a whole.

Number of times we have a requirement where a key-value pair shall exist on its own, for instance:

  • A key-value pair needs to be passed to a method as an argument, Or
  • A method needs to return just two values in form of a pair

Map complicates the things when we just need a single pair of key-value.

Upvotes: 7

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79838

Your choice of which class to use is not just a message to your computer. It's also a message to future developers - people who will maintain your code in the future, or even you yourself in a few months time.

By choosing whether to declare a particular variable as either HashMap or Pair, you're telling those future developers something. It's EITHER

This variable references some kind of map, which uses a hash algorithm for fast retrieval.

OR

This variable references a pair of values.

That will help the future developers to understand what your code is doing. Whereas you can certainly use a HashMap with a single entry instead of a Pair, it would be a very strange thing to do, and it would send entirely the wrong message to the future maintainers of your code.

Upvotes: 28

Nick Clark
Nick Clark

Reputation: 1446

Pair<K, V> is a part of JavaFX whereas Hashmap is in the core API. You can most likely use Pair to create a hashmap implementation (I have not tested this, but I see no reason as to why not), but a Pair is not the same as a HashMap.

Upvotes: -1

Related Questions