Java:从方法调用返回两个int [英] Java: returning two ints from a method call

查看:301
本文介绍了Java:从方法调用返回两个int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的代码中做了很多工作与许多2维坐标:

  int [] getSize {
int [] res = {gridRows,gridColumns};
return res;
}



我知道我可以定义一个小类,并获得类型安全,因为它让我厌烦我有一个琐碎的类在它自己的小琐碎的.java文件,我必须纳入我的代码。



你认为这是丑陋的,坏,还是邪恶?

解决方案

如果有一个概念在你的项目中,你想要封装,例如,这两个int是坐标,没有什么错,为他们有一个类。在我看来,这是很干净,然后强迫所有人创建一个数组等。



例如,是别人在同一个项目中开发,并调用你的方法,认为它们更清楚得到一个int数组有两个位置,或一个对象称为坐标?



此外,您可能需要实现比较坐标,比如坐标,如果使用类,可以封装在正确的OO时尚。 (请记住尊重对象合约,如果您重新定义了等于)。


I do this a lot in my code that works with lots of 2 dimensional coordinates:

int[] getSize() {
    int[] res = {gridRows, gridColumns};
    return res;
}

I know that I could define a tiny class and get type safety but I haven't because it annoys me to have such a trivial class in it's own little trivial .java file that I have to incorporate in my code.

Do you think this is ugly, bad, or evil? Or do you do it too?

解决方案

If there's a concept in your project that you want to encapsulate, for instance, of those two ints are coordinates, there's nothing wrong with having a Class for them. In my opinion that's alot cleaner then forcing everyone to create an array, etc.

For instance, is someone else is developing in the same project and calls your method, do you think it's clearer for them to get a int array with two positions, or an object called Coordinates?

Furthermore, you might want to implement things like comparing coordinates, which could be encapsulated in a correct OO fashion if you use a Class. (Please do remember to respect the Object contract if you redefined something like equals).

这篇关于Java:从方法调用返回两个int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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