• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Searching in ArrayList

 
Ranch Hand
Posts: 367
Eclipse IDE Opera Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,

If my list contains over 1 lac elements then how to effectively search a particular element ?
If the element I'm looking happens to be at the last index then it will take lot of time to search.
Also how contains() work here?
Thanks.
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you're just occasionally searching for one item, it won't take long. You can probably do millions of equality tests per second.

However, finding an item in an unsorted list is an O(N) operation, so if you're doing it a lot, it could become a performance issue. In that case, you would want to sort the List with Collections.sort(), and then use Collections.binarySearch() to find it in O(log N) on an ArrayList.

Another alternative, if you won't have duplicate elements, is to use a SortedHashSet.

As for how contains() works, you can read the docs as well as I can. That's all that's specified. Anything else is left up to the implementation. You can look at the source code to see for yourself if you want. It's in src.zip in your JDK download. However, the most likely implementation for a List is to iterate over the List, comparing each element until we find a match or reach the end of the List.
 
Doe, a deer, a female deer. Ray, a pockeful of sun. Me, a name, I call my tiny ad ...
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic