12

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

I see Pair being introduced to Java version 8

Mani
  • 2,599
  • 4
  • 30
  • 49
  • 3
    `HasMap` is a collection of `Pairs` – Guy Jul 30 '17 at 04:22
  • What is the necessity of having a mutable Hashmap, which can hold multiple pairs, when you just need one? – Tom Jul 30 '17 at 04:22
  • 2
    In what world is `Pair` and `HashMap` doing the same thing? A `Pair` is an object for storing two values, nicknamed `key` and `value`, but might as well be named `foo` and `bar`, since they have no meaning at all to the class. A `HashMap` is an associative data structure mapping unique keys to values. They have nothing in common. – Andreas Jul 30 '17 at 04:41

3 Answers3

25

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.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
6

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.

db07
  • 107
  • 1
  • 6
-1

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.

Nick Clark
  • 1,414
  • 2
  • 16
  • 24