1

我有一个对象数组。对象中有一个 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 "时设置一个标志

4

2 回答 2

3
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少边界检查)

更好的方法:在设置国家值时,检查 if "xxx" 然后立即设置 isXXX,而不需要使用 "check" 算法 :)

于 2012-08-12T15:53:15.643 回答
3

也许使用地图而不是数组。地图应从国家映射到对象。然后您将检查该键是否存在于地图中。

我脑海中的另一个想法是覆盖toString()该类的方法并使用Arrays.toString(custAcctArray).contains("XXX")(或者使用正则表达式进行更可靠的搜索)。但这似乎是一种解决方法。(这是一个相当糟糕的主意。将其视为摆脱代码中循环的一种棘手方法。)

编辑:总结一下我的想法。如果您在初始化数组时知道值“XXX”或使用一组并行的国家/地区值,我认为您应该使用布尔标志(请参阅我的评论)而不是地图。使用 HashSet(效率 O(1)),在这种情况下,您必须覆盖类中equals()hashCode()方法。TreeSet 效率较低(O(log(n))),但在这里您使用比较器或Comparable在您的类中实现接口。

编辑:但是,在这种情况下,我们有String对象,所以不需要实现任何东西(hashCode(),equals()compareTo()在那里实现)。

于 2012-08-12T15:49:34.243 回答