Return more than one value from a function in Java(从 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 中的函数返回多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 Java 中的函数返回多个值


基础教程推荐
- Java Swing计时器未清除 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 多个组件的复杂布局 2022-01-01