我有一个类似于下面的代码片段,
public ArrayList getReport(reportJDOList,accountType)
{
String abc = "";
for(ReportJDO reportJDO : reportJDOList)
{
if(accountType.equals("something")
abc = reportJDO.getThis();
else
abc = reportJDO.getThat();
//somecode goes here
}
returning List;
}
正如我在迭代之前知道accountType的值,我不希望对列表中的每个条目进行此检查,因为如果一个实例的reportJDOList的大小为10000,它将导致大量检查。我们如何消除这件事?在此先感谢:)
答案 0 :(得分:5)
你确实可以执行一次检查并实现2个循环:
if(accountType.equals("something") {
for(ReportJDO reportJDO : reportJDOList) {
abc = reportJDO.getThis();
}
} else {
for(ReportJDO reportJDO : reportJDOList) {
abc = reportJDO.getThat();
}
}
显然,您可以通过
改进设计答案 1 :(得分:4)
如果要保存字符串比较,请在循环之前设置一次并将结果存储在布尔变量中:
String abc = "";
boolean isThis = accountType.equals("something");
for(ReportJDO reportJDO : reportJDOList) {
abc = isThis ? reportJDO.getThis() : reportJDO.getThat();
//somecode goes here
}
答案 2 :(得分:0)
我投票支持干净编码 - 执行一次检查并将逻辑委托给私有方法,每个方法都单独执行循环。这复制了循环的代码,但是如果在某些时候你需要在SomethingReport中做更多的事情,那么在OtherReport中不会重复。
public ArrayList getReport(reportJDOList,accountType) {
if("soemthing".equals(accountType)) {
return getSomethingReport(reportJDOList);
} else {
return getOtherReport(reportJDOList);
}
}
private ArrayList getSomethingReport(reportJDOList) {
[...]
}
答案 3 :(得分:0)
interface AccountHandler {
String get(Report r);
}
AccountHandler thisHandler= new AccountHandler() {
@Override
public String get(Report r) {
return r.getThis();
}
};
AccountHandler thatHandler= new AccountHandler() {
@Override
public String get(Report r) {
return r.getThat();
}
};
//...............
AccountHandler ah;
ah = (what.equalsIgnoreCase("this")) ? thisHandler : thatHandler;
Report r=new Report();
// loop
ah.get(r);
答案 4 :(得分:0)
//Using reflection:
Report r = new Report();
Method thisMethod = r.getClass().getDeclaredMethod("getThis");
Method thatMethod = r.getClass().getDeclaredMethod("getThat");
Method m = (what.equalsIgnoreCase("this")) ? thisMethod : thatMethod;
m.invoke(r);