gpt4 book ai didi

java - 使用常量时替换 if 语句

转载 作者:行者123 更新时间:2023-12-01 23:48:10 25 4
gpt4 key购买 nike

我认为描述我的问题的最佳方式是首先描述我在做什么。

我有一个简单的 Activity ,有 3 个列表选择选项(启动 ListView 的按钮)。每个 ListPicker 在 ListView 中有 8 个项目。

ListView 中的每个项目,我们称其为名称值,都有相应的地址和电话。

这是我正在使用的常量示例

public final String GROUP_1_VENUE_1_NAME = "1name1";
public final String GROUP_1_VENUE_1_ADDRESS = "1address1";
public final String GROUP_1_VENUE_1_PHONE = "1phone1";
public final String GROUP_1_VENUE_2_NAME = "1name2";
public final String GROUP_1_VENUE_2_ADDRESS = "1address2";
public final String GROUP_1_VENUE_2_PHONE = "1phone2";
public final String GROUP_1_VENUE_3_NAME = "1name3";
public final String GROUP_1_VENUE_3_ADDRESS = "1address3";
public final String GROUP_1_VENUE_3_PHONE = "1phone3";
.....

public final String GROUP_2_VENUE_1_NAME = "2name1";
public final String GROUP_2_VENUE_1_ADDRESS = "2address1";
public final String GROUP_2_VENUE_1_PHONE = "2phone1";
public final String GROUP_2_VENUE_2_NAME = "2name2";
public final String GROUP_2_VENUE_2_ADDRESS = "2address2";
public final String GROUP_2_VENUE_2_PHONE = "2phone2";
....

public final String GROUP_3_VENUE_1_NAME = "3name1";
public final String GROUP_3_VENUE_1_ADDRESS = "3address1";
public final String GROUP_3_VENUE_1_PHONE = "3phone1";
public final String GROUP_3_VENUE_2_NAME = "3name2";
public final String GROUP_3_VENUE_2_ADDRESS = "3address2";
public final String GROUP_3_VENUE_2_PHONE = "3phone2";
...

因此从 listPicker 中选取了一个项目,现在我想评估结果

我有3个字符串需要设置;姓名、地址和电话

所以现在我有这样的东西......

if (selection.equals(GROUP_1_VENUE_1_NAME) {
name = GROUP_1_VENUE_1_NAME;
address = GROUP_1_VENUE_1_ADDRESS;
phone = GROUP_1_VENUE_1_PHONE;
} else if (selection.equals(GROUP_1_VENUE_2_NAME) {
name = GROUP_1_VENUE_2_NAME;
address = GROUP_1_VENUE_2_ADDRESS;
phone = GROUP_1_VENUE_2_PHONE;
} else if .....

等等等等。

所以,这是我的问题。有没有更简单的方法可以让我评估选择是否等于名称常量之一,如果是,则设置相应的值?

最佳答案

我认为您需要在以下两个方向改进代码:

创建新的简单类来聚合姓名、电话和地址:

class Contact {
private final String name;
private final String phone;
private final String address;

public Contact(String name, String phone, String address) {
this.name = name;
this.phone = phone;
this.address = address;
}
// getters
}

使用Map来存储选择映射:

private static final Map<String, Contact> selections = new HashMap<String, Contact>();
static {
selections.put("3name1", new Contact("name1", "phone1", "address1"));
// other selections
}

然后您可以通过查找 map 来访问您的联系人:

Contact contact = selections.get(selection);

关于java - 使用常量时替换 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16671579/

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