欢迎访问宙启技术站
智能推送

如何从Java方法中返回多个值?

发布时间:2023-06-27 06:32:19

在Java中,一个方法只能返回一个值。但是有时候我们需要返回多个值,以便在外部使用。有几种方法可以实现这个目标。

1.使用类或结构体

可以使用类或结构体来存储多个值,然后将该对象作为方法的返回值。例如:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person = getPerson();
        System.out.println("Name: "+person.getName()+", Age: "+person.getAge());
    }

    public static Person getPerson() {
        return new Person("Tom", 25);
    }
}

2.使用数组

可以使用数组来存储多个值,然后返回该数组。例如:

public class Main {
    public static void main(String[] args) {
        String[] names = getNames();
        System.out.println("Name 1: "+names[0]+", Name 2: "+names[1]);
    }

    public static String[] getNames() {
        String[] names = new String[2];
        names[0] = "Tom";
        names[1] = "Jerry";
        return names;
    }
}

3.使用Map

可以使用Map来存储多个值,然后返回该Map。例如:

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> student = getStudent();
        System.out.println("Name: "+student.get("name")+", Age: "+student.get("age"));
    }

    public static Map<String, Integer> getStudent() {
        Map<String, Integer> student = new HashMap<String, Integer>();
        student.put("name", "Tom");
        student.put("age", 25);
        return student;
    }
}

4.使用元组

如果您使用Java 8或更高版本,则可以使用javafx.util.Pair类来实现元组。例如:

import javafx.util.Pair;

public class Main {
    public static void main(String[] args) {
        Pair<String, Integer> person = getPerson();
        System.out.println("Name: "+person.getKey()+", Age: "+person.getValue());
    }

    public static Pair<String, Integer> getPerson() {
        return new Pair<String, Integer>("Tom", 25);
    }
}

总之,有多种方法可以从Java方法中返回多个值,每种方法都有其优缺点。根据代码的要求和组织的方式,您可以选择适合您的方法。