gpt4 book ai didi

Java方法返回多个值

转载 作者:行者123 更新时间:2023-11-30 03:09:53 28 4
gpt4 key购买 nike

我有一种情况,我想从一个方法返回 2 个值。我正在尝试弄清楚如何在 Java 中做到这一点。在 C# 中,在这种情况下我只会使用 2 个输出参数或一个结构,但不确定对 Java 最好做什么(除了 Pair 之外,因为我可能必须将其更改为 3 个值,或者必须创建一个新类来返回对象)。

我的例子是这样的:

public void myMethod(Signal signal){
MyEnum enum = MyEnum.DEFAULT;
String country = "";

// based on signal, I need to get 2 values, one is string, other is
// an enumeration
if (signal.getAction() == "Toyota"){
enum = MyEnum.TOYOTA;
country = "Japan";
} else if (signal.getAction() == "Honda"){
enum = MyEnum.HONDA;
country = "Japan";
} else if (signal.getAction() == "VW"){
enum = MyEnum.VW;
country = "Germany";
} else {
enum = MyEnum.DEFAULT;
country = "Domestic";
}

// how to return both enum and country?
return ???
}

这只是一个解释我需要什么的例子(在这种情况下返回一个东西,有两个值,一个是字符串,另一个是枚举)。因此,忽略我的字符串比较或逻辑的任何问题,我的观点是如何返回某些内容。例如,在 C# 中,我可以定义一个结构体并返回该结构体,或者我可以使用 out 参数返回 2 个值。但我不知道如何在 Java 中优雅地做到这一点。

最佳答案

我认为这主要是 Jon Skeet 建议的一个例子。 (经过编辑以包括国家/地区)

让您的枚举携带文本和转换功能。

public enum AutoMake {
HONDA("Honda", "Japan"),
TOYOTA("Toyota", "Japan"),
VW("Volkswagon", "Germany");

private String country;
private String text;

private AutoMake(String text, String country) {
this.text = text;
}

public static AutoMake getMake(String str){
AutoMake make = null;
AutoMake[] possible = AutoMake.values();
for(AutoMake m : possible){
if(m.getText().equals(str)){
make = m;
break;
}
}
return make;
}

/**
* @return the country
*/
public String getCountry() {
return country;
}

/**
* @return the text
*/
public String getText() {
return text;
}

}

然后将品牌作为枚举存储在汽车对象中

public class Car {
private AutoMake make;
private String model;
public Car() {
}
public Car(AutoMake make, String model) {
super();
this.make = make;
this.model = model;
}
/**
* @return the make
*/
public AutoMake getMake() {
return make;
}
/**
* @return the model
*/
public String getModel() {
return model;
}
/**
* @param make the make to set
*/
public void setMake(AutoMake make) {
this.make = make;
}
/**
* @param model the model to set
*/
public void setModel(String model) {
this.model = model;
}
}

现在您可以从汽车对象中获取文本和枚举值

car.getMake() // Enum
car.getMake.getText() // Text
car.getMake.getCountry // Country

您可以使用

将文本转换为枚举
Enum make = AutoMake.getMake("Honda");

这意味着 AutoMake.getMake(Signal.getAction()) 可以将 myMethod(signal) 替换为同时包含品牌和国家/地区的结果 Enum。

关于Java方法返回多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33833168/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com