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

JComboBox.getSelectedIndex: Consider caching the selected index

XMLWordPrintable

      A DESCRIPTION OF THE REQUEST :
      JComboBox.getSelectedIndex() traverses the data list looking for the first match:
          public int getSelectedIndex() {
              Object sObject = dataModel.getSelectedItem();
              int i,c;
              Object obj;

              for ( i=0,c=dataModel.getSize();i<c;i++ ) {
                  obj = dataModel.getElementAt(i);
                  if ( obj != null && obj.equals(sObject) )
                      return i;
              }
              return -1;
          }



        Given that the selected item's index is known when set, couldn't the JComboBox cache this index and return that value each time instead of iterating/looking. If the underlying model changes the JComboBox could do a rescan then and recache the selected index.

      JUSTIFICATION :
      will be quicker

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      quick retrieval of the index
      ACTUAL -
      a possible complete iteration of the model

      ---------- BEGIN SOURCE ----------
      import javax.swing.*;
      import java.awt.*;


      public class JComboBoxSelectedIndex implements Runnable{

          public void run(){
      Integer[] data = new Integer[Integer.MAX_VALUE/100];
              for(int i = 0; i < Integer.MAX_VALUE/100; i++)
                  data[i] = i;
              JComboBox jcb = new JComboBox(data);
              jcb.setSelectedIndex(Integer.MAX_VALUE/100 -1);
              System.out.println("GETTING SELECTED INDEX....");
              long time1 = System.currentTimeMillis();
              jcb.getSelectedIndex();
              long time2 = System.currentTimeMillis();
              System.out.println("Took:: " + (time2 -time1));


          }

          public static void main(String ... args){
              SwingUtilities.invokeLater(new JComboBoxSelectedIndex());
          }

      }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      The user could override the set methods and cache there.

            Unassigned Unassigned
            tyao Ting-Yun Ingrid Yao (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Imported:
              Indexed: