我有这样的方法:
public boolean isDocumentsDeletedFormDB(String strDocumentsID) {
}
在这种方法中,我也想返回一个Integer
值。由于已经有一个返回类型 as Boolean
,我怎样才能返回Integer
值呢。
将WrapperInteger
作为协议传递也不能解决我的问题。
Collection
任何人都可以在不使用返回类型的情况下提出解决方案。
首先我必须说你的方法有问题;一个方法必须只做一件事,而您的方法必须做两件事(计算您需要返回的两个值)。正确的解决方案是创建另一个方法,该方法的目的是返回其中一个值,而另一个由原始方法返回。
无论如何,如果你真的需要这样做,你有一些选择:
返回多个元素的标准方法是返回封装这些元素的对象。
例如:
public static class DeletedFromDBReturn {
public final int integerValue;
public final bool booleanValue;
private DeletedFromDBReturn(int i, bool b) {
integerValue = i; booleanValue = b;
}
}
DeletedFromDBReturn sDocumentsDeletedFormDB(String strDocumentsID) {
// ...
return new DeletedFromDBReturn(intVal, boolVal);
}
您可以做的是将返回类型更改为int
. 其他-1
情况下返回false
Valid integer.
从方法名称我可以猜到您使用boolean
返回类型来检查文档是否被删除。而Integer
你想要的回报将会number of documents deleted
。
public int isDocumentsDeletedFormDB(String strDocumentsID) {}
因此您可以签入使用此功能的功能
if(isDocumentsDeletedFormDB(str)==-1)
//Do that you do when it is false.
您可能想要使用一个简单的字符串,它可以返回这两种类型,但以字符串形式。在您的调用代码中,只需检查它是否为(“true”或“false”)并相应地解析它。
您不能从 Java 中的函数返回多个值。您必须使用集合或类或结构来包含这 2 个值。
您必须定义一个具有Boolean
andInteger
字段的对象并返回该对象,否则,如果您可以使用外部库,您可以查看Pair<L,R>
Apache Commons 提供的类。
创建一个普通的旧 Java 对象(POJO) 类并返回它的一个实例。你的 POJO 类可以是这样的:
public class MyPOJO{
private boolean booleanValue;
private Integer integerValue;
public void setBooleanValue(boolean booleanValue){
this.booleanValue = booleanValue
}
public void setIntegerValue(Integer integerValue){
this.integerValue = integerValue
}
public boolean getBooleanValue(){
return this.booleanValue;
}
public Integer getIntegerValue(){
return this.integerValue;
}
}
您需要更改方法签名并执行以下操作:
public MyPOJO isDocumentsDeletedFormDB(String strDocumentsID){
/*
* Your logic
*/
MyPOJO pojo = new MyPOJO();
pojo.setIntegerValue(/* Your integer value */);
pojo.setBooleanValue(/* Your boolean value */);
return pojo;
}
您可以编写一个通用的 Pair<First,Second> 类并返回一个 Pair<Boolean,Integer>。但是恕我直言,您也应该考虑更改方法名称,因为每个人都希望名为 isSomething() 的方法只返回布尔值。