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

查看:27
本文介绍了在 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 类通常很有用,我创建了一个通用的 Pair 类(这可能是您的想法).返回数组是一种快速而简单的方法,但您以后可能会后悔,因为使用您的方法的人会怀疑该方法是否会在某个时刻返回两个以上的值.

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 时,您都应该考虑使用例如一个通用的 Pair 类对于下一个阅读代码的人来说确实值得丢失信息(这个人很可能在六个月后就是你).为返回类型编写一个单独的类现在需要更多时间,但它会向使用您的方法的人传达更多信息(即,它告诉用户返回值代表什么,并包含两个值的有用成员名称).不过,如果是非公开的方法,只用在少数地方,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天全站免登陆