从 Java 中的函数返回多个值 [英] Return more than one value from a function in Java

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

问题描述

如何从 Java 中的函数返回多个值?任何人都可以提供使用元组执行此操作的示例代码吗?我无法理解元组的概念.

How to return more than one value from a function in Java? Can anyone give sample code for doing this using tuples? I am not able to understand the concept of tuples.

public class Tuple{
    public static void main(String []args){
        System.out.println(f());
    }
    static Pair<String,Integer> f(){
        return new Pair<String,Integer>("hi",3);
    }
    public class Pair<String,Integer> {
        public final String a;
        public final Integer b;

        public Pair(String a, Integer b) {
            this.a = a;
            this.b = b;
        }
    }
}

上面的代码有什么错误?

What is the mistake in the above code?

推荐答案

创建一个包含您需要的多个值的类.在您的方法中,返回一个作为该类实例的对象.瞧!

Create a class that holds multiple values you need. In your method, return an object that's an instance of that class. Voila!

这样,您仍然返回 一个 对象.在 Java 中,您不能返回超过 一个 的对象,无论它是什么.

This way, you still return one object. In Java, you cannot return more than one object, whatever that may be.

这篇关于从 Java 中的函数返回多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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