問題描述
我有一組對象.每個對象都有 String 值.
I have Set of objects. Each object has String value.
我需要選擇所有 this
值等于direction"的對象.
I need to select all objects that have this
value equal to "direction".
是否可以不迭代集合?
推薦答案
一般來說,沒有.您需要遍歷集合并檢查每個對象以查看屬性是否等于您正在搜索的值.這是一個 O(n)
操作.
In general, no. You need to iterate over the set and check each object to see if the property is equal to the value you are searching for. This is an O(n)
operation.
在一種情況下,您無需迭代即可完成.如果您的對象的 equals
方法是根據該 String
屬性的相等性定義的,并且如果 hashCode
方法也正確實現,那么您可以使用 hashSet.contains
在 O(1)
時間內找到具有正確值的對象,而無需遍歷集合.
There is one situation in which you could do it without iterating. If your object's equals
method is defined in terms of equality of that String
property, and if the hashCode
method is also implemented correctly, then you can use the hashSet.contains
to find an object with the correct value in O(1)
time without requiring iterating over the set.
正如我所提到的,這是一個非常具體的用例,而不是通用解決方案.如果字符串是某種唯一標識符,它可能會很有用,但它不適用于您的特定用例.
As I mentioned, this is a very specific use case and not a general solution. It might be useful if the string was some sort of unique identifier, but it won't work for your specific use case.
您可能還想考慮其他更適合您的用例的集合.例如,如果您使用 Guava,那么您可以考慮使用 多地圖.
You might also want to consider other collections that would be better suited to your use case. You could for example if you are using Guava then you could consider using a Multimap.
相關
- HashMap在同一個鍵下有多個值
這篇關于如果 Set 包含具有某些字符串值的對象,如何檢查 java?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!