(coll) Optimization for LinkedList's indexOf and lastIndexOf methods

XMLWordPrintable

    • Type: Enhancement
    • Resolution: Not an Issue
    • Priority: P5
    • None
    • Affects Version/s: 1.4.1
    • Component/s: core-libs

      LinkedList.indexOf could take advantage of the fact that "header" entry has a null element for increased performance when it is passed a null "target":

          public int indexOf(Object o) {
              int index = 0;
              if (o==null) {
                  // header.element guaranteed null, no chance of looping past header
                  for (Entry e = header.next; e.element != null; e = e.next) {
                      index++;
                  }
                  // if index < size, null was found, else we looped to header
                  return (index < size) ? index: -1;
              } else {
                  for (Entry e = header.next; e != header; e = e.next) {
                      if (o.equals(e.element))
                          return index;
                      index++;
                  }
              }
              return -1;
          }

      Applying a similar transformation to lastIndexOf yields very pretty results:

          public int lastIndexOf(Object o) {
              int index = size - 1;
              if (o==null) {
                  for (Entry e = header.previous; e.element != null;
                       e = e.previous, index--);
              } else {
                  for (Entry e = header.previous; e != header && !o.equals(e.element);
                       e = e.previous, index--);
              }
              return index;
          }

            Assignee:
            Unassigned
            Reporter:
            Josh Bloch (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: