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 中的函数返回多个值


- C++ 和 Java 进程之间的共享内存 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01