在Java中返回一对值的最佳方式是什么? [英] What's the best way to return a pair of values in Java?

查看:307
本文介绍了在Java中返回一对值的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个小问题,因为我可以轻松地鞭打一双课来做这个工作。我真的不想这样做,我觉得应该有一些简单的,内置的,类似java的返回两个值的方法。你们是最好的,最简单的做法?数组?一些其他数据结构?

This is a small issue, as I could easily whip up a pair class to do the job. I don't really want to do this though, and I feel like there should be some simple, built-in, java-like way of returning two values. What do you guys is the best, simplest way of doing this? Arrays? Some other data structure?

推荐答案

据我所知,不幸的是,Java中没有内置的一对表示我当然希望有)。就个人而言,当我编写一个项目时,我发现一个对经常会很有用,我创建一个通用的 Pair< T,U> 类(这可能是你是思考)。返回一个数组是一种快速而简单的方法,但是以后可能会后悔,因为使用方法的人会想知道方法是否可能在某个时候返回两个以上的值。

As far as I know, there is unfortunately no built-in representation of a pair in Java (and I certainly wish there was). Personally, when I code a project where I find that a pair class often would be useful, I create a generic Pair<T, U> class (which is probably what you were thinking of). Returning an array is a fast and simple way, but you might come to regret it later, because people who use your method will wonder whether the method might at some point return more than two values.

无论您选择哪种解决方案:每当您觉得需要一对时,您应该考虑是否使用例如一般的Pair类真的值得丢失信息给下一个读取代码的人(而且那个人在六个月内可能会是你)。为返回类型编写一个单独的类现在需要更多的时间,但它会传达更多的信息给那些使用你的方法(即它告诉用户什么是返回值表示,并包含两个值的有用的成员名称)。但是,如果这是一种非公开的方法,那么只能使用几个地方,那么一对更可以接受。

Whichever solution you choose: whenever you feel that you need a Pair, you should consider whether the time saved today by using e.g. a generic Pair class really is worth the loss of information to the next person who reads the code (and that person may well be you in six months). Writing a separate class for the return type takes more time now, but it would convey more information to those that use your method (namely, it tells the users what the return value represents, and contains useful member names for the two values). If it is a non-public method that is used only a few places, though, a Pair is more acceptable.

这篇关于在Java中返回一对值的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆