Anuj Balan
Anuj Balan

Reputation: 7729

Efficient way of checking for a value present in an object, from an array of objects

I have an array of objects. There is a getCountry() in the object. I want to set a flag when the getCountry() is equal to say 'XXX'.

As of know, I am doing,

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....
}

I somehow don't like this logic when I assume the array is filled with some 100 or odd objects. Can someone throw or shed light at other ways of achieving the final output in an efficient way? What I want: set a flag when getCountry() == "XXX"

Upvotes: 1

Views: 131

Answers (2)

Vic
Vic

Reputation: 1888

Maybe use a map instead of an array. The map should map from country to object. Then you will check whether the key exist in the map.

Another idea from the top of my head is to override the toString() method of that class and use Arrays.toString(custAcctArray).contains("XXX") (or maybe more reliable search using regexp). But it looks like a workaround. (This one is rather bad idea. Think about that as a tricky way to get rid of the loop in your code.)

Edit: To summarize my thoughts. Instead of a map, I think you should use a boolean flag (see my comment) if you know the value "XXX" when initializing the array or use a parallel set of country values. Use HashSet (efficiency O(1)), in this case you have to override equals() and hashCode() methods in your class. TreeSet is less efficient (O(log(n))) and still, here you use comparator or implement the interface Comparable in your class.

Edit: However, in this case we have String objects, so no need to implement anything (hashCode(), equals() and compareTo() are implemented there).

Upvotes: 3

huseyin tugrul buyukisik
huseyin tugrul buyukisik

Reputation: 11920

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....
}

Do you see the break; ? This exits the big loop as soon as possible. If you dont, the next iteration could set it to other value.

You can also use a "separate" array outside the object to access it quicker(1 less bounds checking)

A better way: when setting the country values, check that if "xxx" then set isXXX rightaway without needing to use a "check" algortihm :)

Upvotes: 3

Related Questions