Java 是否存在私有布尔(基元)字段变量默认为非false的情况?
假设我有一个类DisplaySpecificType.java,它扩展了抽象类DisplayBase.java。在我的课堂上,我有几个领域:Java 是否存在私有布尔(基元)字段变量默认为非false的情况?,java,spring,boolean,default-value,Java,Spring,Boolean,Default Value,假设我有一个类DisplaySpecificType.java,它扩展了抽象类DisplayBase.java。在我的课堂上,我有几个领域: private boolean noData; private List<String> selections; private List<Integer> intSelections; 以下是准备方法: protected List<Integer> prepareSelections(String dataStri
private boolean noData;
private List<String> selections;
private List<Integer> intSelections;
以下是准备方法:
protected List<Integer> prepareSelections(String dataString) {
String trimmedData = StringUtils.trimToNull(dataString); // Empty strings -> null
selections = new ArrayList<String>();
if (trimmedData == null) {
noData = true;
} else {
// Do some operations on trimmedData, convert to integers
// (in String format) and add to selections array
}
intSelections = new ArrayList<Integer>();
if (!noData) {
for (String index : selections) {
int num = Integer.parseInt(index) - 1;
intSelections.add(num);
}
}
return intSelections;
}
我无法从Eclipse运行应用程序,因为它与其他几个应用程序交互,但我有几个单元测试Junit来测试功能。创建DataHolder对象并在测试中设置dataString不会导致任何问题,而且一切都很顺利
然而,实际上,运行调用该类的应用程序会导致intSelections变为空,即使dataString不是空的。在使用if/else语句之外的trimmedValues中的数据填充选择值之后,我立即记录了选择值,该语句在应该填充时使用了正确的数据。然后我在填充它的for循环之后记录了intSelections的值,令我惊讶的是,它是空的
所以我会有这样的东西:
记录器:选择=[1,2,3]
记录器:intSelections=[]
如果选择包含数据,则无法将noData布尔值设置为true。但是很明显,填充intSelections的if语句被忽略了,这让我认为noData已经被设置为true
在prepare方法开始时将noData初始化为false修复了这个问题,但我仍然不明白为什么
我们使用spring、maven和MOM队列,但我对它们的执行方式并不十分熟悉。我知道spring配置中没有设置任何属性,它只是在服务上下文中通过Springbean初始化DisplaySpecificType类
对不起,这个冗长的问题,有人知道这里发生了什么吗
编辑:
正如我在评论中提到的,以下是我认为发生的事情:
我假设发出给主应用程序命令的每个命令都会进入并最终被我的项目解析,DataHolder和dataString就是从这里来的,它会创建这个类的一个新实例,但情况可能并非如此 如果传递的输入导致dataString为null或空,则noData将设置为true,如果实例未被销毁,则在传递下一个输入时将保持true。我不太清楚应用程序如何与所有其他程序交互,所以这只是我最好的猜测 是否存在私有布尔基元字段变量 默认值不是false吗 不。正如其他人所提到的,您的代码中肯定存在其他问题。根据 4.12.5。变量的初始值 程序中的每个变量都必须有一个值,然后才能确定其值 使用: 每个类变量、实例变量或数组组件都是 创建§15.9、§15.10时,使用默认值初始化: 对于boolean类型,默认值为false。
我很抱歉。我还是不明白这个问题。如果trimmedata==null,则将noData设置为true,它不会初始化为true。dataString必须为空或null。默认情况下,布尔实例字段将始终初始化为false。一定是有什么东西在修改它。我假设发出给主应用程序命令的每个命令都会进入并在我的项目中进行解析,而DataHolder和` dataString就是从这里来的,它会创建这个类的一个新实例,但我的假设可能是错误的。@ElliottFrisch如果传递的输入导致dataString为null或空,则noData将设置为true,如果实例未销毁,则在传递下一个输入时将保持true。这是一个巨大的互联程序网络,有点难以理解。谢谢你的帮助。
protected List<Integer> prepareSelections(String dataString) {
String trimmedData = StringUtils.trimToNull(dataString); // Empty strings -> null
selections = new ArrayList<String>();
if (trimmedData == null) {
noData = true;
} else {
// Do some operations on trimmedData, convert to integers
// (in String format) and add to selections array
}
intSelections = new ArrayList<Integer>();
if (!noData) {
for (String index : selections) {
int num = Integer.parseInt(index) - 1;
intSelections.add(num);
}
}
return intSelections;
}