Java collection insertion: Set vs. List

后端 未结 7 890
花落未央
花落未央 2021-02-14 10:56

I\'m thinking about filling a collection with a large amount of unique objects. How is the cost of an insert in a Set (say HashSet) compared to an List (say ArrayList)?

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-14 11:43

    Java List:

    If you don't have such requirement that you have to keep duplicate or not. Then you can use List instead of Set.

    List is an interface in Collection framework. Which extends Collection interface. and ArrayList, LinkedList is the implementation of List interface.

    When to use ArrayList or LinkedList

    ArrayList: If you have such requirement that in your application mostly work is accessing the data. Then you should go for ArrayList. because ArrayList implements RtandomAccess interface which is Marker Interface. because of Marker interface ArrayList have capability to access the data in O(1) time. and you can use ArrayList over LinkedList where you want to get data according to insertion order.

    LinkedList: If you have such requirement that your mostly work is insertion or deletion. Then you should use LinkedList over the ArrayList. because in LinkedList insertion and deletion happen in O(1) time whereas in ArrayList it's O(n) time.

    Java Set:

    If you have requirement in your application that you don't want any duplicates. Then you should go for Set instead of List. Because Set doesn't store any duplicates. Because Set works on the principle of Hashing. If we add object in Set then first it checks object's hashCode in the bucket if it's find any hashCode present in it's bucked then it'll not add that object.

提交回复
热议问题