Is there a good reason why there is no Pair<L,R>
in Java? What would be the equivalent of this C++ construct? I would rather avoid reimplementing my own.
It seems that 1.6 is providing something similar (AbstractMap.SimpleEntry<K,V>
), but this looks quite convoluted.
Five alternatives to Pair class in Java | Techie Delight. FAANG Interview Preparation Practice. Data Structures and Algorithms. Array Binary Tree Binary Search Tree Dynamic Programming Divide and Conquer Backtracking Linked List Matrix Heap Stack Queue String Graph Sorting.
There are two types of Pair classes in Java, which are as follows: Immutable Pair Class: The Immutable Pair classes are such classes in which the value of the object cannot be changed if once defined; that means we cannot use the setters method to alter the defined values.
Pair<Integer, String> pair = new Pair<>(1, "One"); Integer key = pair. getKey(); String value = pair. getValue(); This example illustrates a simple Integer to String mapping using the Pair concept.
In Java, a tuple is a generic data structure that treats each element as an object, and these objects stores in a separate byte array. In other words, we can also say that tuple is an ordered collection of objects of different types.
In a thread on comp.lang.java.help
, Hunter Gratzner gives some arguments against the presence of a Pair
construct in Java. The main argument is that a class Pair
doesn't convey any semantics about the relationship between the two values (how do you know what "first" and "second" mean ?).
A better practice is to write a very simple class, like the one Mike proposed, for each application you would have made of the Pair
class. Map.Entry
is an example of a pair that carry its meaning in its name.
To sum up, in my opinion it is better to have a class Position(x,y)
, a class Range(begin,end)
and a class Entry(key,value)
rather than a generic Pair(first,second)
that doesn't tell me anything about what it's supposed to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With