问题描述:

I want to check if an item exists in an item set.

I want to do this in java:

def is_item_in_set(item, item_set):

if item in item_set:

return true

else:

return false

(Apologies if my python is not pythonic. Just wanted to convey my intent.)

I've managed writing this:

boolean isItemInSet(String item, String[] itemSet) {

for(int i =0; i < itemSet.length; ++i) {

if(item.equals(itemSet[i])) {

return true;

}

}

return false;

}

Is there a better way for testing set-membership in Java?

网友答案:

You can't do it with a straight array, but you can with a Set<T> by calling .contains. If you feel like you will be doing a lot of isItemInSet calls, consider using Sets instead of arrays -- you will be much happier.

For example, using a HashSet<T> makes isItemInSet an O(1) operation (on average). Set insertion and deletion are also similarly fast. Indeed, a HashSet<T> in Java is essentially the same as a Python set() (similar underlying concept and performance characteristics) -- you will see a big improvement in speed with many calls to query, insert or delete on the set.

相关阅读:
Top