gpt4 book ai didi

java - 枚举作为 Java 中常量的替代品

转载 作者:行者123 更新时间:2023-11-29 07:01:58 24 4
gpt4 key购买 nike

有一天我听说我们应该使用枚举而不是常量。在所有情况下都可能吗? 枚举是否替代了常量

在下面的示例中,我在常量文件中定义了常量,ConstantsTest 使用它们

public final class Constants {

private Constants(){

}
public static final String ACCOUNT="Account";
public static final String EVENT_ITEM ="EventItem";
public static final int MULTIPLIER_ONE = 1;
public static final int MULTIPLIER_NEGATIVE_ONE = -1;
public static final String BALANCE_AFTER_MODIFICATION = "BalanceAfterModification";
public static final String COMMA = ",";
public static final String DOTPSV =".psv";
public static final String NEW_LINE = "\n";
}


// Test Class
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ConstantsTest {
private static File rootDir = new File(".");
public static void main(String[] args) throws IOException {

Map<String,Integer> accountBalance = new HashMap<String, Integer>();
accountBalance.put("123",55000);
accountBalance.put("223",15000);
writeToFile(Constants.ACCOUNT, accountBalance, true, 2000);
// do operation

}

/**
*
* @param fileType
* @param inputData
* @param add if true add balance else substract the balance
* @return
* @throws IOException
*/
private static File writeToFile(String fileType , Map<String,Integer>accountBalance ,boolean add, int amount) throws IOException{
File file = null;
FileWriter fw = null;
try{
if(Constants.ACCOUNT.equals(fileType)){
file = new File(rootDir,Constants.ACCOUNT+Constants.DOTPSV);//creating a fileName using constants
fw = new FileWriter(file);
fw.write(Constants.ACCOUNT+Constants.COMMA+Constants.BALANCE_AFTER_MODIFICATION);//Writing Header in file using constant values
updateBalance(accountBalance, add, amount);
for(String key:accountBalance.keySet()){
fw.write(Constants.NEW_LINE);
fw.write(key+Constants.COMMA+accountBalance.get(key));
}
}
else if(Constants.EVENT_ITEM.equals(fileType))
{
// write to EventItem.psv
}
} finally{
if (null!=fw){
fw.close();
}
}

System.out.println("File created successfully");
return file;

}

private static void updateBalance(Map<String, Integer> accountBalance,
boolean add, int amount) {
for(String key:accountBalance.keySet()){
int currentBal = accountBalance.get(key);
if(add){
accountBalance.put(key,currentBal+amount*Constants.MULTIPLIER_ONE); // do lot of calculations
}else{
accountBalance.put(key,currentBal+amount*Constants.MULTIPLIER_NEGATIVE_ONE);// do a lot of calculations
}
}
}

}

请在我的示例中建议枚举会更好或者我目前使用常量的方法已经足够好

最佳答案

在您的特定情况下,使用枚举是经典解决方案。

首先,让我们将您的常量重写为枚举:

public enum Constants {
ACCOUNT,
EVENT_ITEM,
;

}

public enum Operation {
MULTIPLIER_ONE {
public int action(int value) {
return value;
}
},
MULTIPLIER_NEGATIVE_ONE {
public int action(int value) {
return value * (-1);
}
},
;
private Operation(int coef) {
this.coef = coef;
}

public abstract int action(int value);
}

现在不用写了:

if(Constants.ACCOUNT.equals(fileType)){
} else if(....)

您可以使用 switch/case 或更好地定义:define 方法(让我们将其称为 action() 到枚举中并从您的代码中调用它。参见示例在上面的 Operation 枚举中。在这种情况下,您的代码变得微不足道:不再有 if/else 或 switch 语句。一切都很简单。验证在编译时完成:您定义了 abstract枚举中的方法,如果不为其实现此方法,则无法向枚举添加另一个元素。使用 if/else 结构时不会发生这种情况,维护是程序员的责任。

我只知道枚举的一个限制:在注释中使用字符串常量。有很多带有字符串属性的注解。例如 XmlElement(name="foo")。即使你定义枚举

enum FooBar {
foo, bar
}

你不能在注释中使用它:

@XmlElement(name=FooBar.foo) // is wrong because String type is required
@XmlElement(name=FooBar.foo.name()) // is wrong because annotations do not support method invocation

在所有其他情况下,我更喜欢枚举。

关于java - 枚举作为 Java 中常量的替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24524371/

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