是否应该使用 Java 方法参数来返回多个值? [英] Should Java method arguments be used to return multiple values?

查看:27
本文介绍了是否应该使用 Java 方法参数来返回多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于在 Java 中发送给方法的参数指向调用者方法中的原始数据结构,它的设计者是否打算将它们用于返回多个值,就像 C 等其他语言中的规范一样?

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 ?

或者这是对 Java 的一般属性(变量是指针)的危险滥用吗?

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

推荐答案

很久以前我和 Ken Arnold(曾经是 Java 团队的成员)有过一次谈话,这可能是在第一次 Java One 会议上,所以 1996 年.他说他们正在考虑添加多个返回值,以便您可以编写如下内容:

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.

基于此以及 Java 工作人员的其他评论,我会说目的是/是您返回一个类的实例,而不是修改传入的参数.

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.

这是常见的做法(就像 C 程序员希望修改参数一样......最终他们看到了通常的 Java 方式.把它想象成返回一个结构体.:-)

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)

我正在读取一个文件并生成两个数组,类型为 String 和 int from它,为两者选择一个元素每条线.我想返回两个他们到任何调用它的函数以这种方式拆分哪个文件.

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<Line> lines)
{
    // add to the List.
}

然后像这样调用它:

{
    final List<Line> lines;

    lines = new ArrayList<Line>();
    foo(file, lines);
}

这篇关于是否应该使用 Java 方法参数来返回多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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