<Swing Dev> 6179357: Generics: JList: getSelectedValues
Florian Brunner
fbrunnerlist at gmx.ch
Tue Dec 30 20:55:14 UTC 2008
Hi,
I hope you all had a Merry Christmas! I started now to add generics to ListModel and JList. While adding generics to the ListModel is quite straightforward, I think, there
are some issues with JList, I would like to dicuss. I start here with the first issue: getSelectedValues
Am I right, that there is no way to change the signature of this method to:
public E[] getSelectedValues()
where E is the type parameter of the class?
(Because of generic array creation, which is not supported by Java.)
Here is the current implementation:
public Object[] getSelectedValues() {
ListSelectionModel sm = getSelectionModel();
ListModel dm = getModel();
int iMin = sm.getMinSelectionIndex();
int iMax = sm.getMaxSelectionIndex();
if ((iMin < 0) || (iMax < 0)) {
return new Object[0];
}
Object[] rvTmp = new Object[1+ (iMax - iMin)];
int n = 0;
for(int i = iMin; i <= iMax; i++) {
if (sm.isSelectedIndex(i)) {
rvTmp[n++] = dm.getElementAt(i);
}
}
Object[] rv = new Object[n];
System.arraycopy(rvTmp, 0, rv, 0, n);
return rv;
}
If this is not possible I propose to add a new method:
public List<E> getSelectedItems()
and deprecate getSelectedValues:
...
* @deprecated As of JDK 1.7, replaced by {@link #getSelectedItems()}
*/
@Deprecated
public Object[] getSelectedValues() {
...
}
/**
* Returns a list of all the selected items, in increasing order based
* on their indices in the list.
*
* @return the selected items, or an empty list if nothing is selected
* @see #isSelectedIndex
* @see #getModel
* @see #addListSelectionListener
*
* @since 1.7
*/
public List<E> getSelectedItems() {
ListSelectionModel sm = getSelectionModel();
ListModel<? extends E> dm = getModel();
int iMin = sm.getMinSelectionIndex();
int iMax = sm.getMaxSelectionIndex();
if ((iMin < 0) || (iMax < 0)) {
return Collections.emptyList();
}
List<E> selectedItems = new ArrayList<E>();
for(int i = iMin; i <= iMax; i++) {
if (sm.isSelectedIndex(i)) {
selectedItems.add(dm.getElementAt(i));
}
}
return selectedItems;
}
Note: Ignore for now 'E' vs '? extends E', I will start another thread for this. I'm just interested if you think it's a good idea to add the getSelectedItems method and to
deprecate getSelectedValues.
So I wish you a Happy New Year and hope to hear from you soon.
-Florian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.openjdk.java.net/pipermail/swing-dev/attachments/20081230/42ef0817/attachment.html>
More information about the swing-dev
mailing list