我有一个对象数组。对象中有一个 getCountry()。我想在 getCountry() 等于“XXX”时设置一个标志。
据我所知,我正在做,
boolean isXXX=false;
if(custAcctArray != null)
{
for(int index=0;index<custAcctArray.length;index++)
{
if(custAcctArray[i].getCountry().equalsIgnoreCase("XXX"))
{
isXXX=true;
}
}
}
if(isXXX)
{
Do something about it....
}
当我假设数组中填充了大约 100 个或奇数个对象时,我不知何故不喜欢这种逻辑。有人可以抛出或阐明以有效方式实现最终输出的其他方式吗? 我想要的:当 getCountry() == "XXX"
时设置一个标志最佳答案
boolean isXXX=false;
if(custAcctArray != null)
{
for(int index=0;index<custAcctArray.length;index++)
{
if(custAcctArray[i].getCountry().equalsIgnoreCase("XXX"))
{
isXXX=true;
break;//<-------------you need to exit to be quick and true solution!!!!
}
}
}
if(isXXX)
{
Do something about it....
}
你看到休息了吗? ?这样可以尽快退出大循环。如果不这样做,下一次迭代可以将其设置为其他值。
您还可以在对象外部使用“单独的”数组来更快地访问它(减少 1 个边界检查)
更好的方法:在设置国家/地区值时,检查是否“xxx”然后立即设置 isXXX,而无需使用“检查”算法 :)
关于java - 从对象数组中检查对象中存在的值的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11923479/