Java Equivalent of C Pair
Question:
Although Java has Map.Entry in 1.6, it does not have a direct equivalent of C 's Pair
Answer:
Reasons for Absence:
Hunter Gratzner, in a comp.lang.java.help thread, presents arguments against introducing a Pair construct in Java. The primary concern is that a Pair class lacks explicit semantics about the relationship between its two values. Without specific naming, it's unclear what the "first" and "second" values represent, making understanding the intent of code more challenging.
Suitable Alternative:
The recommended approach is to create simple and specific classes for each intended use case. For example, instead of Pair(x,y), a more descriptive class like Position(x,y) conveys the relationship between the two values more clearly. Similarly, for Range(begin,end) and Entry(key,value).
Map.Entry as a Limited Equivalent:
While Map.Entry provides a pair-like functionality, it is specific to key-value mappings, limiting its general-purpose applicability.
Conclusion:
Instead of resorting to generic Pair classes, Java encourages the creation of specialized and meaningful classes that convey the intended use explicitly. This approach enhances code readability and understanding, while avoiding the semantic ambiguity associated with a generic Pair type.
The above is the detailed content of What's the Java Equivalent of C 's `Pair` and Why Isn't There a Direct Analogue?. For more information, please follow other related articles on the PHP Chinese website!