从 Java 中的函数返回多个值

2022-01-20 00:00:00 tuples return-type 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.

相关文章