--- old/src/java.desktop/share/classes/javax/swing/JList.java 2018-01-05 15:32:17.437289549 +0530 +++ new/src/java.desktop/share/classes/javax/swing/JList.java 2018-01-05 15:32:17.237289549 +0530 @@ -2359,26 +2359,37 @@ /** * Selects the specified object from the list. + * If the object passed is not present in the list, the selection is + * cleared. * * @param anObject the object to select * @param shouldScroll {@code true} if the list should scroll to display * the selected object, if one exists; otherwise {@code false} */ public void setSelectedValue(Object anObject,boolean shouldScroll) { - if(anObject == null) - setSelectedIndex(-1); - else if(!anObject.equals(getSelectedValue())) { + E selectedValue = getSelectedValue(); + //This will be true if both anObject and selectedObject are either + // null or point to objects which return true on calling equals + if((anObject == selectedValue) || + (anObject != null && anObject.equals(selectedValue))) { + return; + } else { int i,c; ListModel dm = getModel(); - for(i=0,c=dm.getSize();i(dlm); + list.setSelectionMode( + ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + dlm.addElement("1"); + dlm.addElement(null); + dlm.addElement("2"); + + // Select first two elements added in list + list.setSelectionInterval(0, 2); + checkSelectionByArray(list, new String[]{"1", null, "2"}); + + // Set the selected value as null. This should select the + // null element in the list + list.setSelectedValue(null, true); + checkSelectionByArray(list, new String[]{null}); + + // Select first two elements added in list + list.setSelectionInterval(0, 1); + checkSelectionByArray(list, new String[]{"1", null}); + + // Set the selected value as some object not present in the + // list. This should clear the selection + list.setSelectedValue("4", true); + checkSelectionByArray(list, new String[0]); + } + }); + } + + static void checkSelectionByArray(JList list, String[] selectionArray) + throws RuntimeException { + Object[] arraySelection = list.getSelectedValuesList().toArray(); + if (!Arrays.equals(arraySelection, selectionArray)) { + System.out.println("Expected: " + selectionArray); + System.out.println("Actual: " + arraySelection); + throw new RuntimeException("Wrong selection"); + } + } +}