Why doesn't java.util.Set have get(int index)?

前端 未结 18 1367
长情又很酷
长情又很酷 2020-11-28 18:14

I\'m sure there\'s a good reason, but could someone please explain why the java.util.Set interface lacks get(int Index), or any similar get()

18条回答
  •  悲哀的现实
    2020-11-28 18:54

    Please note only 2 basic data structure can be accessed via index.

    • Array data structure can be accessed via index with O(1) time complexity to achieve get(int index) operation.
    • LinkedList data structure can also be accessed via index, but with O(n) time complexity to achieve get(int index) operation.

    In Java, ArrayList is implemented using Array data structure.

    While Set data structure usually can be implemented via HashTable/HashMap or BalancedTree data structure, for fast detecting whether an element exists and add non-existing element, usually a well implemented Set can achieve O(1) time complexity contains operation. In Java, HashSet is the most common used implementation of Set, it is implemented by calling HashMap API, and HashMap is implemented using separate chaining with linked lists (a combination of Array and LinkedList).

    Since Set can be implemented via different data structure, there is no get(int index) method for it.

提交回复
热议问题