题目是个 伪命题 ,由Java语法我们都知道,方法要么返回一个对象,要么就不返回
当有这样的情况,我们需要返回两个或多个对象,该怎么做呢?
1.多对象封装成单个类中的多个字段
这种方法详细各位都能理解,无非就是新建一个类,然后类里面再有几个字段即可
class MyResult {
Student student;
People people;
//省略get/set方法和构造方法
}
public MyResult test(){
Student student = new Student();
People people = new People();
return new MyResult(student,people);
}
但如果我们情况比较多的话,每次新建类都很麻烦,有没有更方便的一种使用呢?
当然是有的,我们可以使用Pair类
2.使用 Pair 类和 MutableTriple 类
Pair 和 MutableTriple 都是lang3包中提供的,所以要使用,得先加入依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8</version>
</dependency>
还是上面的例子,我们可以使用Pair改造一下
public Pair<Student,People> test(){
Student student = new Student();
Peopl

本文介绍了在Java中如何在方法中返回两个或多个对象,包括将对象封装到单独的类中,使用Apache的Pair和Triple类,以及Kotlin中的Pair和Triple类的简要说明。
最低0.47元/天 解锁文章
938

被折叠的 条评论
为什么被折叠?



