HashSet vs ArrayList contains performance

前端 未结 5 687
一整个雨季
一整个雨季 2020-12-14 05:55

When processing large amounts of data I often find myself doing the following:

HashSet set = new HashSet ();
//Adding elements to         


        
5条回答
  •  既然无缘
    2020-12-14 06:27

    The ArrayList uses an array for storing the data. The ArrayList.contains will be of O(n) complexity. So essentially searching in array again and again will have O(n^2) complexity.

    While HashSet uses hashing mechanism for storing the elements into their respective buckets. The operation of HashSet will be faster for long list of values. It will reach the element in O(1).

提交回复
热议问题