Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 768935
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T18:15:29+00:00 2026-05-14T18:15:29+00:00

Why Methode LinkedList.contains() runs quickly than such implementation: for (String s : list) if

  • 0

Why Methode LinkedList.contains() runs quickly than such implementation:

for (String s : list) 
   if (s.equals(element))
     return true;
return false;

I don’t see great difference between this to implementations(i consider that search objects aren’t nulls), same iterator and equals operation

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T18:15:30+00:00Added an answer on May 14, 2026 at 6:15 pm

    Let’s have a look at the source code (OpenJDK version) of java.util.LinkedList

    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }
    public int indexOf(Object o) {
        int index = 0;
        if (o==null) {
            /* snipped */ 
        } else {
            for (Entry e = header.next; e != header; e = e.next) {
                if (o.equals(e.element))
                    return index;
                index++;
            }
        }
        return -1;
    }
    

    As you can see, this is a linear search, just like the for-each solution, so it’s NOT asymptotically faster. It’d be interesting to see how your numbers grow with longer lists, but it’s likely to be a constant factor slower.

    The reason for that would be that this indexOf works on the internal structure, using direct field access to iterate, as opposed to the for-each which uses an Iterator<E>, whose methods must also additionally check for things like ConcurrentModificationException etc.

    Going back to the source, you will find that the E next() method returned by the Iterator<E> of a LinkedList is the following:

    private class ListItr implements ListIterator<E> {
       //...
       public E next() {
          checkForComodification();
          if (nextIndex == size)
          throw new NoSuchElementException();
    
          lastReturned = next;
          next = next.next;
          nextIndex++;
          return lastReturned.element;
      }
      final void checkForComodification() {
          if (modCount != expectedModCount)
             throw new ConcurrentModificationException();
      }
    

    This is considerably “busier” than the e = e.next; in LinkedList.contains! The iterator() of a LinkedList is actually a ListIterator, which has richer features. They aren’t needed in your for-each loop, but unfortunately you have to pay for them anyway. Not to mention all those defensive checks for ConcurrentModificationException must be performed, even if there isn’t going to be any modification to the list while you’re iterating it.


    Conclusion

    So yes, iterating a LinkedList as a client using a for-each (or more straightforwardly, using its iterator()/listIterator()) is more expensive than what the LinkedList itself can do internally. This is to be expected, which is why contains is provided in the first place.

    Working internally gives LinkedList tremendous advantage because:

    • It can cut corners in defensive checks since it knows that it’s not violating any invariants
    • It can take shortcuts and work with its internal representations

    So what can you learn from this? Familiarize yourself with the API! See what functionalities are already provided; they’re likely to be faster than if you’ve had to duplicate them as a client.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 434k
  • Answers 434k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer find_month_first_monday I'd use a different algorithm. First, find the first… May 15, 2026 at 3:09 pm
  • Editorial Team
    Editorial Team added an answer The best way I found was this http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs namespace MvcApplication1.Models… May 15, 2026 at 3:09 pm
  • Editorial Team
    Editorial Team added an answer May I suggest you take a look at the cron_schedule… May 15, 2026 at 3:09 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.