JDK-4947273 : (coll) Create a standard Pair class (based on C++ pair class)
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Priority: P4
  • Status: Closed
  • Resolution: Won't Fix
  • Submitted: 2003-10-31
  • Updated: 2017-07-21
  • Resolved: 2017-07-21
Related Reports
Duplicate :  
Description

Name: rmT116609			Date: 10/31/2003


A DESCRIPTION OF THE REQUEST :
A standard pair class would assist developers who constantly write such helper classes.

JUSTIFICATION :
This class is simple to write and would go a long way towards making code more readable as we would not so many little classes which are all 99% the same. Also, could be the base class for other objects and replace Map.Entry which in my opinion should have been an immutable Pair object which would have simplified writing Map implementations, i.e. having an actual class instead of having to re-implement (which while easy is tiresome).

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
I would like pair classes that are mutable, immutable & thread-safe. I would also like second parameters to be optiunal based on either an inheritance model or something else. I also would like a pair that supports the Comparable interface. Note that equals(), hashCode() and toString() should be overridden and implemented to handle first and second.
ACTUAL -
Pair p = new Pair(new Integer(3), "abcde");
p.getFirst();
p.getSecond();
p.toString();

CUSTOMER SUBMITTED WORKAROUND :
I wrote my own pair class.

Pair - optional second
StrictPair - second required
MutablePair - mutable
ComparablePair - first and second are comparable and non-null
ThreadsafePair - mutable and thread-safe
(Incident Review ID: 218844) 
======================================================================

Comments
Per the above comment, we need to await language features that support this more effectively. Meanwhile, we won't add a pure library-based Pair class. Even when the language gains better facilities, it's unclear whether the library should have a single "Pair" construct that is expected to satisfy everybody's needs, or whether applications are better off creating their own on an as-needed basis. Closing as Won't Fix.
21-07-2017

Pair somehow manages to touch on all the flaws in Java: nullability (of components and the pair itself), mutability (including race conditions), erasure-based generics, boxing overheads. I don't think we should try to deal with it until we get the right tools in the language, notably value types and full specialization; at that point there may be a place for pair-values. For now, folks can easily define their own pairs, even as local classes, or else use Map::entry (new in 9).
17-07-2017