Hey, guys. I have a homework assignment due later tonight and am having a bit of trouble. I have to sort an array list as part of the assignment. My understanding is that must use Collections.sort, but I can't get that to work. I am not sure if that is due to my use of generics or what. Here is my current code.
and the error messages I am getting are:
I've looked at quite a few explanations of sorting arraylists, and they all achieve sorting with Collections.sort( ArrayList );, but this isn't working for me. They all used string values for sorting and I am using numbers, but it seems like Collections.sort would be able to sort values of the Number type. Any help would be great. Let me know if I left out something you need to know.
If you look at the JavaDoc for the Collections class, you will see that the sort() method that takes one parameter, takes a generic that is an upper bound of Comparable. The generic that you defined doesn't fulfill that requirement.
You have a few options... (1) you can create a new list that takes a comparable generic, and copy your elements over, (2) you can add an upper bound to your class to require that the type be comparable, or (3) you can use a comparator instead, as that sort method doesn't have that requirement.
The easiest of these options, is option 2... which means that you have to change your class as follows...
Ah, thank you. That seems to have worked. Believe it or not, I did look at the javadoc; it's just that I don't really know how to read the documentation, or how to learn how to read and understand it. I saw
and thought I just inserted a list (I assumed arraylist would work because I saw it in other peoples' code) of type T. Now that I've read your post I notice the
beside it, but I didn't know what that meant, nor that I could do <T extends Number & Comparable<? super T>>.
I see that if you click "sort" it takes you to a more detailed explanation, but when I looked at it earlier I saw
and didn't understand that I could do the same thing to a class, where as here it was a method.