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 中的函数返回多个值
基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01