Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of the C++ Pair<L,R> in Java?

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.

like image 995
David Segonds Avatar asked Oct 01 '08 04:10

David Segonds


People also ask

What is equivalent of pair in Java?

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.

Is there a pair type in Java?

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.

How do you initialize a pair in Java?

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.

Is there tuple in Java?

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.


1 Answers

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.

like image 189
Luc Touraille Avatar answered Oct 11 '22 13:10

Luc Touraille