C++ Pair class equivalent in Java

September 30, 2016

In the standard Java library, there is not Pair class. When you want to use Pair you have some options.

1. Create new class.

For example, you want to create a pair of name-price items; better is create a new class, containing field name and price. It will improve code readability, and you can add own method unique to the product.

2. Use one of many similar implementations based on key-value

For example, you use:

  • javafx.util.Pair

and access it:
  • java.util.AbstractMap.SimpleEntry

now you can get key/value:

3. Implementing own Pair class

You can also create it, below I show a basic example of own Pair class:

Now when you have Pair class you can create new Object:

and access field by:

 

Click here to add a comment

Leave a comment: