What is the equivalent of the C++ Pair in Java?

前端 未结 30 1033
一个人的身影
一个人的身影 2020-11-22 02:29

Is there a good reason why there is no Pair in Java? What would be the equivalent of this C++ construct? I would rather avoid reimplementing my own.<

30条回答
  •  [愿得一人]
    2020-11-22 03:01

    As many others have already stated, it really depends on the use case if a Pair class is useful or not.

    I think for a private helper function it is totally legitimate to use a Pair class if that makes your code more readable and is not worth the effort of creating yet another value class with all its boiler plate code.

    On the other hand, if your abstraction level requires you to clearly document the semantics of the class that contains two objects or values, then you should write a class for it. Usually that's the case if the data is a business object.

    As always, it requires skilled judgement.

    For your second question I recommend the Pair class from the Apache Commons libraries. Those might be considered as extended standard libraries for Java:

    https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html

    You might also want to have a look at Apache Commons' EqualsBuilder, HashCodeBuilder and ToStringBuilder which simplify writing value classes for your business objects.

提交回复
热议问题