0
DefaultListModel<String> strings = new DefaultListModel<String>();
DefaultListModel<Integer> integers = new DefaultListModel<Integer>();

private <T> void sortList(DefaultListModel<T> defaultListModel)
{
    T objects[] = (T[])defaultListModel.toArray(); 

    defaultListModel.clear();

    Arrays.sort(objects);

    for (T object: objects)
    {
        defaultListModel.addElement(object);
    }
}



how can i write the above without getting an unchecked cast warning and without using @suppress?

johnny
  • 258
  • 2
  • 12

1 Answers1

0

You are not doing anything worng. The reason for unchecked cast warning is because the DefaultListModel toArray() method is not generic . it returns an Object array which when you type cast to your generic class array T[] , compiler gives the warning. You can avoid the warnings by putting the below line above your method sortList:-

@SuppressWarnings("unchecked")
private <T> void sortList(DefaultListModel<T> defaultListModel)
{
      .....
}
Manjunath
  • 1,685
  • 9
  • 9
  • 1
    i dont want to suppress warnings, i want to suppress my mistakes, lack of knowledge and improve my understanding. – johnny Sep 08 '14 at 19:06
  • how can i make so that its T[]? – johnny Sep 08 '14 at 20:33
  • @johnny There is nothing that I am aware of that you can do to actually fix this warning except suppressing it reason being the DefaultListModel is a class in rt.jar as part of jdk 7 and above which we cannot modify. Had the toArray method in the DefaultListModel provided in the JDK been generic (just like the class is) this warning wouldnot have come. So my bet is you just need to supress the warning. – Manjunath Sep 09 '14 at 04:02
  • i recently read an article that stated what id written was correct and that receiving the warning was "normal". thanks for your repsone. – johnny Sep 09 '14 at 20:28