如果Java方法的参数用来返回多个值? [英] Should Java method arguments be used to return multiple values?

查看:743
本文介绍了如果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 ?

推荐答案

一个很久以前我有过一次交谈与肯·阿诺德(在Java团队一次成员),这将是在可能是第一个Java的一个会议上,所以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. :-)

(基于以下注释编辑)

我读一个文件,并生成二
  数组类型为String和INT从,
  它,从采摘一个元素为
  每一行。我想返回两个
  他们需要将呼叫它的任何功能
  其中一个文件拆分这种方式。

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.

我想,如果我理解正确你,我谓可能会做soemthing是这样的:

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.
}

然后调用它是这样的:

and then call it like this:

{
    final List<Line> lines;

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

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

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