How to obtain index of a given LinkedHashSet element without iteration?

后端 未结 8 1652
無奈伤痛
無奈伤痛 2020-12-14 16:45

Is it even possible?

Say you have

private Set names = new LinkedHashSet();

and Strings ar

相关标签:
8条回答
  • 2020-12-14 17:04

    A Set is "a collection that contains no duplicate elements," and it does not maintain order of its elements. http://download.oracle.com/javase/6/docs/api/java/util/Set.html

    The code you have given will not necessarily return 1 every time. Iterating through a Set is not guaranteed to iterate in the same order every time; it is only guaranteed to iterate over each element once.

    Since you seem to care about the order of the elements, you need to be using a List instead of a Set.

    0 讨论(0)
  • 2020-12-14 17:11

    It is generally not possible for a Set to return the index because it's not necessarily well defined for the particular Set implementation. For example it says in the HashSet documentation

    It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.

    So you shouldn't say the type is Set when what you actually expect is a Set implementing som order.

    0 讨论(0)
提交回复
热议问题