Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><a href="http://java.sun.com/javase/6/docs/api/java/util/Collections.html" rel="noreferrer"><code>Collections.binarySearch()</code></a>.</p> <p>Assuming the cats are sorted by birthday, this will give the index of one of the cats with the correct birthday. From there, you can iterate backwards and forwards until you hit one with a different birthday.</p> <p>If the list is long and/or not many cats share a birthday, this should be a significant win over straight iteration.</p> <p>Here's the sort of code I'm thinking of. Note that I'm assuming a <a href="http://java.sun.com/javase/6/docs/api/java/util/RandomAccess.html" rel="noreferrer">random-access</a> list; for a linked list, you're pretty much stuck with iteration. (Thanks to fred-o for pointing this out in the comments.)</p> <pre><code>List&lt;Cat&gt; cats = ...; // sorted by birthday List&lt;Cat&gt; catsWithSameBirthday = new ArrayList&lt;Cat&gt;(); Cat key = new Cat(); key.setBirthday(...); final int index = Collections.binarySearch(cats, key); if (index &lt; 0) return catsWithSameBirthday; catsWithSameBirthday.add(cats.get(index)); // go backwards for (int i = index-1; i &gt; 0; i--) { if (cats.get(tmpIndex).getBirthday().equals(key.getBirthday())) catsWithSameBirthday.add(cats.get(tmpIndex)); else break; } // go forwards for (int i = index+1; i &lt; cats.size(); i++) { if (cats.get(tmpIndex).getBirthday().equals(key.getBirthday())) catsWithSameBirthday.add(cats.get(tmpIndex)); else break; } return catsWithSameBirthday; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload