java函数参数返回,如果Java方法的参数用来返回多个值?

这篇博客探讨了Java中方法参数传递的本质,指出Java设计者原本考虑支持多重返回值,但最终推荐通过创建返回类来实现。作者引用与Java团队成员的早期对话,强调返回一个包含多个数据成员的类实例是最佳实践,而不是修改传入的参数。博客提供了具体的代码示例,展示如何通过自定义类来返回两个数组。
摘要由CSDN通过智能技术生成

Since arguments sent to a method in Java point to the original data structures in the caller method, did its designers intend for them to used for returning multiple values, as is the norm in other languages like C ?

Or is this a hazardous misuse of Java's general property that variables are pointers ?

解决方案

A long time ago I had a conversation with Ken Arnold (one time member of the Java team), this would have been at the first Java One conference probably, so 1996. He said that they were thinking of adding multiple return values so you could write something like:

x, y = foo();

The recommended way of doing it back then, and now, is to make a class that has multiple data members and return that instead.

Based on that, and other comments made by people who worked on Java, I would say the intent is/was that you return an instance of a class rather than modify the arguments that were passed in.

This is common practice (as is the desire by C programmers to modify the arguments... eventually they see the Java way of doing it usually. Just think of it as returning a struct. :-)

(Edit based on the following comment)

I am reading a file and generating two

arrays, of type String and int from

it, picking one element for both from

each line. I want to return both of

them to any function which calls it

which a file to split this way.

I think, if I am understanding you correctly, tht I would probably do soemthing like this:

// could go with the Pair idea from another post, but I personally don't like that way

class Line

{

// would use appropriate names

private final int intVal;

private final String stringVal;

public Line(final int iVal, final String sVal)

{

intVal = iVal;

stringVal = sVal;

}

public int getIntVal()

{

return (intVal);

}

public String getStringVal()

{

return (stringVal);

}

// equals/hashCode/etc... as appropriate

}

and then have your method like this:

public void foo(final File file, final List lines)

{

// add to the List.

}

and then call it like this:

{

final List lines;

lines = new ArrayList();

foo(file, lines);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值