javaswingjlistselectionmodel

Why Jlist is selecting index 0 even when the item is not present there


Why Jlist is selecting index 0 even when the item is not present there.

Here is my code I have created a JList lst and set its content as a vector vct which consists of objects of class people which when invoked toString() provides with details of people.Which look like this,

screenshot of the problem

now when I run this code which is invoked when I press ctrl+F and if I enter "alfozen" into the input dialog, then it selects 1st, 3rd item,5th and 7th, no matter what I search the index 0(1st item) is always shown selected,This is my first question at stackOverflow , please let me know if I should provide more information on the issue.Thanks a lot in advance

this is the code,

if ((ke.getKeyCode() == KeyEvent.VK_F) && ((ke.getModifiers() & 
KeyEvent.CTRL_MASK) != 0))
{
 int i=0,j=0;

 lst.clearSelection();
 lst.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

 String s=JOptionPane.showInputDialog("Enter Name to search : ");
   if(s==null)return;

 String arg[]=new String[vct.size()];
 int arr[]=new int[vct.size()];

 for(people p : vct)
 {
  arg[i++]=p.toString();
 }

for(j=0,i=0;j<arg.length;j++)
{
 if(arg[j].contains(s))
 {
  arr[i++]=j;
 }
}
lst.setSelectedIndices(arr);
lst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}

Solution

  • That would be because you told it to.

    After your loops, the first i elements of arr contain the indices that match. What do the rest contain? Well, you never assigned anything to them, so they hold the default int value 0.

    So if you have 5 elements, and the second, third and fifth elements match, then ar contains 1, 2, 4, 0, 0.

    So when you call lst.setSelectedIndices(arr);, elements 1, 2, 4, 0 and 0 are selected.