Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-4679639

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

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Not an Issue
    • Icon: P5 P5
    • None
    • 1.4.1
    • 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;
          }

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

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: